Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

SwiftUI Documentation

Posts under SwiftUI tag

2,338 Posts
Sort by:
Post not yet marked as solved
0 Replies
5 Views
Has anyone successfully persisted Color, particularly in SwiftData? So far my attempts have failed: Making Color conform to Codable results in a run time error (from memory something about ColorBox). Color.Resolved already conforms Codable but this results in "SwiftData/ModelCoders.swift:124: Fatal error: Composite Coder only supports Keyed Container" I am now attempting to save CGColor in the SwiftData model and handle the conversion to and from Color via a custom property wrapper. However, I have made mistake somewhere in its implementation down below I have seen that SwiftData has @Attribute(.transformable(by: CustomValueTransformer.self)) but I am not sure how to implement the ValueTransformer because the conversion between Color to CGColor needs to read from the environment when using the new Color.resolve(in: ) method (Color.cgColor is now deprecated). I could avoid using a custom property wrapper but before I do I want to know if anyone has solved my problem in a better way? import SwiftUI @propertyWrapper struct ColorBinding: DynamicProperty { @Binding var color: CGColor @Environment(\.self) var environment var wrappedValue: Color { get { Color(color) } nonmutating set { color = newValue.resolve(in: environment).cgColor } } var projectedValue: Binding<Color> { Binding { wrappedValue } set: { wrappedValue = $0 } } } struct View1: View { @State private var cgColor = CGColor( red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: .random(in: 0...1) ) var body: some View { View2(color: $cgColor) // Cannot convert value of type 'Binding<CGColor>' to expected argument type 'ColorBinding' } } struct View2: View { @ColorBinding var color: Color var body: some View { ColorPicker("", selection: $color) } } #Preview { View1() }
Posted
by Uasmel.
Last updated
.
Post not yet marked as solved
0 Replies
5 Views
This is a bug I have been trying to identify and fix for more than 3 weeks. This bug mostly happens in production. The stack trace doesn't help that much, because it looks like the app is crashing due to some SwiftUI internal methods. I tried everything in my power to debug and find this bug, still nothing. Due to the lack of 100% reproducibility, it made me think that this bug is either memory-pressure related or Swift concurrency related. When does it happen: This bug happens when presenting a SwiftUI modal (UIViewControllerRepresentable)[A] which in terms presents a UIHostingController modal[B] which then presents a modally a SwiftUI sheet [C] The bug happens somewhere around staying in [C] or after dismissing it. Context: The app lifecycle is SwiftUI. The main SwiftUI screen in the app body is a UIViewControllerRepresentable containing a UISplitViewController. Here is a screenshot from the crash log in Xcode. Anyone facing a similar issue?
Posted Last updated
.
Post not yet marked as solved
0 Replies
66 Views
Hello, my production app is experiencing some crashes according to app store analytics. I cannot seem to reproduce it. According to Xcode Orginzer the app is crashing 10 SwiftUI 0x000000018ec372a0 PlatformViewHost.updateNestedHosts(_:colorSchemeChanged:) + 332 (PlatformViewHost.swift:699) Distributor ID: com.apple.AppStore Hardware Model: iPhone13,4 Version: 2.0.3 (86) AppStoreTools: 15E204 AppVariant: 1:iPhone13,4:16 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] OS Version: iPhone OS 17.4.1 (21E236) Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 6 Abort trap: 6 Triggered by Thread: 0 Kernel Triage: VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter Thread 0 name: Thread 0 Crashed: 0 libsystem_kernel.dylib 0x00000001d1bd6974 __pthread_kill + 8 (:-1) 1 libsystem_pthread.dylib 0x00000001e56590ec pthread_kill + 268 (pthread.c:1717) 2 libsystem_c.dylib 0x0000000191627c14 __abort + 136 (abort.c:159) 3 libsystem_c.dylib 0x0000000191627b8c abort + 192 (abort.c:126) 4 libswiftCore.dylib 0x000000018832a690 swift::fatalErrorv(unsigned int, char const*, char*) + 136 (Errors.cpp:387) 5 libswiftCore.dylib 0x000000018832a6b0 swift::fatalError(unsigned int, char const*, ...) + 32 (Errors.cpp:395) 6 libswiftCore.dylib 0x0000000188324a08 getNonNullSrcObject(swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::TargetMetadata&lt;swift::InProcess&gt; const*) + 256 (DynamicCast.cpp:144) 7 libswiftCore.dylib 0x0000000188326510 tryCastToObjectiveCClass(swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::TargetMetadata&lt;swift::InPro... + 88 (DynamicCast.cpp:510) 8 libswiftCore.dylib 0x0000000188324068 tryCast(swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::TargetMetadata&lt;swift::InProcess&gt; const*&amp;, sw... + 992 (DynamicCast.cpp:2281) 9 libswiftCore.dylib 0x0000000188323b14 swift_dynamicCast + 208 (CompatibilityOverrideRuntime.def:109) 10 SwiftUI 0x000000018ec372a0 PlatformViewHost.updateNestedHosts(_:colorSchemeChanged:) + 332 (PlatformViewHost.swift:699) 11 SwiftUI 0x000000018ec36bf4 PlatformViewHost.updateEnvironment(_:viewPhase:) + 412 (PlatformViewHost.swift:690) 12 SwiftUI 0x000000018ec37bf8 PlatformViewHost.init(_:host:environment:viewPhase:importer:) + 808 (PlatformViewHost.swift:132) 13 SwiftUI 0x000000018ec36cf8 PlatformViewHost.__allocating_init(_:host:environment:viewPhase:importer:) + 92 (PlatformViewHost.swift:0) 14 SwiftUI 0x000000018ec0132c closure #1 in closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 444 (PlatformViewRepresentable.swift:559) 15 SwiftUI 0x000000018ec06c58 partial apply for closure #1 in closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 24 (&lt;compiler-generated&gt;:0) 16 SwiftUI 0x000000018ea26910 RepresentableContextValues.asCurrent&lt;A&gt;(do:) + 156 (RepresentableContextValues.swift:43) 17 SwiftUI 0x000000018ec01124 closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 176 (PlatformViewRepresentable.swift:558) 18 SwiftUI 0x000000018ec0104c closure #4 in closure #1 in PlatformViewChild.updateValue() + 128 (PlatformViewRepresentable.swift:557) 19 SwiftUI 0x000000018ec06b2c partial apply for closure #4 in closure #1 in PlatformViewChild.updateValue() + 24 (&lt;compiler-generated&gt;:0) 20 SwiftUI 0x000000018de7b7d0 closure #1 in _withObservation&lt;A&gt;(do:) + 44 (ObservationUtils.swift:26) 21 SwiftUI 0x000000018ec06b50 partial apply for closure #1 in _withObservation&lt;A&gt;(do:) + 24 (&lt;compiler-generated&gt;:0) 22 libswiftCore.dylib 0x0000000187fd0068 withUnsafeMutablePointer&lt;A, B&gt;(to:_:) + 28 (LifetimeManager.swift:82) 23 SwiftUI 0x000000018ebffbdc closure #1 in PlatformViewChild.updateValue() + 3040 (PlatformViewRepresentable.swift:556) 24 SwiftUI 0x000000018d5ecbf8 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init&lt;A&gt;(_:) + 32 (&lt;compiler-generated&gt;:0) 25 AttributeGraph 0x00000001b2150240 AG::Graph::UpdateStack::update() + 512 (ag-graph-update.cc:578) 26 AttributeGraph 0x00000001b2146f38 AG::Graph::update_attribute(AG::data::ptr&lt;AG::Node&gt;, unsigned int) + 424 (ag-graph-update.cc:719) 27 AttributeGraph 0x00000001b2146810 AG::Graph::input_value_ref_slow(AG::data::ptr&lt;AG::Node&gt;, AG::AttributeID, unsigned int, unsigned int, AGSwiftMetadata const*, unsigned char&amp;, long) + 720 (ag-graph.cc:1429)
Posted
by RFusion.
Last updated
.
Post not yet marked as solved
2 Replies
382 Views
I am generating a USD file with RealityKit and ARKit. I want to, within the same app, open the USD file and display it as if it was a USDZ file. For the user to see, without having to send it to another device. Is this possible? Thanks
Posted Last updated
.
Post not yet marked as solved
0 Replies
37 Views
When the content exceeds 40 lines of text, crazy behaviour starts to happen. The content jumps up and down while typing. Is there any other way to implement simple editor that can handle around 200 lines without this crazy behaviour?
Posted
by m4rqs.
Last updated
.
Post not yet marked as solved
0 Replies
56 Views
I have a container view implementation that reads preference values from child views: public struct Reader<Content>: View where Content: View { public var content: () -> Content public init(@ViewBuilder content: @escaping () -> Content) { self.content = content } public var body: some View { content() .onPreferenceChange(NumericPreferenceKey.self) { value in // ... } } } This works fine until the content passed in to the container view is a Group. At that point the onPreferenceChanged modifier is applied to every child of the group, which leads to bugs in my situation. One thing I can do is simply put the content in a VStack: public var body: some View { VStack(content: content) .onPreferenceChange(NumericPreferenceKey.self) { value in // ... } } And that works fine to "Ungroup" before applying the onPreferenceChanged modifier. However, is this best practice? Is there a better way to apply a modifier to content as a whole instead of to each member of a potential group? Is it concerning that I might have an extra VStack in the view hierarchy with this fix?
Posted
by rolson.
Last updated
.
Post marked as solved
1 Replies
45 Views
I'm running into this error, when the underlying SwiftData object changes (gets an object added to it): *" A NavigationLink is presenting a value of type “Project” but there is no matching navigationDestination declaration visible from the location of the link. The link cannot be activated. Note: Links search for destinations in any surrounding NavigationStack, then within the same column of a NavigationSplitView. "* For instance, when I first fire up the simulator, clicking on any existing project correctly takes me to its details page. However, as soon as I add a new project or delete a project, none of the navigation links work any more. If I reload the simulator, they all work again! Makes me suspect it's an error with not recomputing the links when the underlying data change, but I can't figure out what I need to change, as everything looks correct. Any help would be appreciated! ContentView: struct ContentView: View { @Environment(\.modelContext) var modelContext @Query(sort: \Project.endDate) var projects: [Project] var body: some View { NavigationStack { Group { if projects.isEmpty { ContentUnavailableView("Enter your first project.", systemImage: "clipboard") } else { List { ForEach(projects, id: \.id) { project in NavigationLink(value: project) { HStack { DaysTile( days: project.numWorkDaysNowUntilEnd, description: "Work Days Remaining" ) .padding(.trailing, 5) VStack(alignment: .leading) { Text(project.name) .font(.title) Text("Start: \(project.startDate.formatted(date: .abbreviated, time: .omitted))") .foregroundStyle(.secondary) Text("End: \(project.endDate.formatted(date: .abbreviated, time: .omitted))") .foregroundStyle(.secondary) } } } } .onDelete(perform: deleteProjects) } .navigationDestination(for: Project.self) { project in ProjectDetailView(project: project) } } } .navigationTitle("Project Tracker") .toolbar { NavigationLink { AddProjectView() } label: { Label("Add New Project", systemImage: "plus") } } } } func deleteProjects(at offsets: IndexSet) { for offset in offsets { let project = projects[offset] modelContext.delete(project) } } } #Preview { ContentView() .modelContainer(for: Project.self, inMemory: true) }
Posted Last updated
.
Post not yet marked as solved
1 Replies
50 Views
Hello, I am doing to load model from bundle and it is loaded successfully. Now I am scaling model using GestureExtension from apple demo code. (https://developer.apple.com/documentation/realitykit/transforming-realitykit-entities-with-gestures?changes=_8) @State private var selectedEntityName : String = "" @State private var modelEntity: ModelEntity? var body: some View { contentView .task { do { modelEntity = try await ModelEntity.loadArcadeMachine() } catch { fatalError(error.localizedDescription) } } } @ViewBuilder private var contentView: some View { if let modelEntity { RealityView { content, attachments in modelEntity.position = SIMD3<Float>(x: 0, y: -0.3, z: -5) print(modelEntity.transform.scale) modelEntity.transform.scale = [0.006, 0.006, 0.006] content.add(modelEntity) if let percentTextAttachment = attachments.entity(for: "percentage") { percentTextAttachment.position = [0, 50, 0] modelEntity.addChild(percentTextAttachment) } } update: { content, attachments in // I want here to get updated scaling value and it is showing in RealityView attachmnt text. } attachments: { Attachment(id: "percentage") { Text("\(modelEntity.name) \(modelEntity.scale * 100) %") .font(.system(size: 5000)) .background(.red) } } // This method am using for gesture support .installGestures() } else { ProgressView() } } } Below code from GestureExtension let state = EntityGestureState.shared guard canScale, !state.isDragging else { return } let entity = value.entity if !state.isScaling { state.isScaling = true state.startScale = entity.scale } let magnification = Float(value.magnification) entity.scale = state.startScale * magnification state.magnifyValue = magnification magnifyScale = Double(magnification) print("Entity Name ::::::: \(entity.name)") print("Scale ::::::: \(entity.scale)") print("Magnification ::::::: \(magnification)") print("StartScale ::::::: \(state.startScale)") > This "magnification" value I need to use in RealityView class. How can i Do it? Could you please guide it. }
Posted Last updated
.
Post not yet marked as solved
5 Replies
4.7k Views
Any one getting any issues with NavigaitonLink to seemingly innocuous views freezing when tapped on? 1 CPU at 100% memory steadily increasing until app gets killed by the system. Will freeze if any NavigationLink on the view is tapped if certain views are linked to using NavigaitonLink. I note some people have been getting similar freezes if they use @AppStorage, but I'm not using @AppStorage. I do use CoreData tho. tho I have some views that use core data that don't freeze. https://developer.apple.com/forums/thread/708592?page=1#736374022 has anyone experienced similar issues? or know the cause. it doesn't seem to be any of my code because if I pause the debugger it stops on system code.
Posted
by ngb.
Last updated
.
Post not yet marked as solved
1 Replies
244 Views
@Query(filter: #Predicate<Note>{ note in note.isDeleted == false && (note.title != "" || note.content != "") } ,sort: [SortDescriptor(\Note.isPinned, order: .reverse),SortDescriptor(\Note.createdAt, order: .reverse)] , animation: .smooth(duration: 0.3) ) private var notes: [Note] if I delete filter part navigationLink works properly
Posted
by AzizK.
Last updated
.
Post not yet marked as solved
0 Replies
62 Views
When I build app on Xcode 15.3 with SWIFT_STRICT_CONCURRENCY=complete, there are some warning. Almost warning can be fixed, but not the TipKit code. Here is the example. Are there any good way to solve it?
Posted
by hcrane.
Last updated
.
Post marked as solved
4 Replies
185 Views
On my shop and content views of my app, I have a shopping cart SF symbol that I've modified with a conditional to show the number of items in the cart if the number of items is above zero. However, whenever I change tabs and back again, that icon disappears even though there should be an item in the cart. I have a video of the error, but I have no idea how to post it. Here is some of the code, let me know if you need to see more of it: CartManager.swift import Foundation import SwiftUI @Observable class CartManager { /*private(set)*/ var products: [Product] = [] private(set) var total: Int = 0 private(set) var numberofproducts: Int = 0 func count() -> Int { numberofproducts = products.count return numberofproducts } func addToCart(product: Product) { products.append(product) total += product.price numberofproducts = products.count } func removeFromCart(product: Product) { products = products.filter { $0.id != product.id } total -= product.price numberofproducts = products.count } } ShopPage.swift import SwiftUI struct ShopPage: View { @Environment(CartManager.self) private var cartManager var columns = [GridItem(.adaptive(minimum: 135), spacing: 0)] @State private var searchText = "" let items = ["LazyHeadphoneBean", "ProperBean", "BabyBean", "RoyalBean", "SpringBean", "beanbunny", "CapBean"] var filteredItems: [Bean] { guard searchText.isEmpty else { return beans } return beans.filter { $0.imageName.localizedCaseInsensitiveContains(searchText) } } var body: some View { NavigationStack { ZStack(alignment: .top) { Color.white .ignoresSafeArea(edges: .all) VStack { AppBar() .environment(cartManager) ScrollView() { LazyVGrid(columns: columns, spacing: 20) { ForEach(productList, id: \.id) { product in NavigationLink { beanDetail(product: product) .environment(cartManager) } label: { ProductCardView(product: product) .environment(cartManager) } } } } } .navigationBarDrawer(displayMode: .always)) } } .environment(cartManager) } var searchResults: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.contains(searchText)} } } } #Preview { ShopPage() .environment(CartManager()) } struct AppBar: View { @Environment(CartManager.self) private var cartManager var body: some View { NavigationStack { VStack (alignment: .leading){ HStack { Spacer() NavigationLink(destination: CartView() .environment(cartManager) ) { CartButton(numberOfProducts: cartManager.products.count) } } Text("Shop for Beans") .font(.largeTitle .bold()) } } .padding() .environment(CartManager()) } } CartButton.swift import SwiftUI struct CartButton: View { var numberOfProducts: Int var body: some View { ZStack(alignment: .topTrailing) { Image(systemName: "cart.fill") .foregroundStyle(.black) .padding(5) if numberOfProducts > 0 { Text("\(numberOfProducts)") .font(.caption2).bold() .foregroundStyle(.white) .frame(width: 15, height: 15) .background(Color(hue: 1.0, saturation: 0.89, brightness: 0.835)) .clipShape(RoundedRectangle(cornerRadius: 50)) } } } } #Preview { CartButton(/*numberOfProducts: 1*/numberOfProducts: 1) }
Posted
by KittyCat.
Last updated
.
Post not yet marked as solved
4 Replies
68 Views
I encountered a problem while using ScrollView in SwiftUI. When I perform a refresh, the app crashes. I access the array using an index in a ForEach loop. This is done to create new data from the array in a commonly used view. The function to create data is adopted from a protocol in the view model. I access it by index because the type of the array is not specified; each view using it may have a different data type. Below is an example code. Is it possible to access data from the array using an index? Every time I refresh, I get an "index out of range" error. import SwiftUI struct ContentView: View { @StateObject var viewModel = ViewModel() var body: some View { ScrollView { if !viewModel.testValues.isEmpty { LazyVStack(spacing: 20) { ForEach(Array(zip(viewModel.testValues.indices, viewModel.testValues)), id:\.1) { index, data in test(index: index, data: data, viewModel: viewModel) .onAppear { if !viewModel.isLoading, viewModel.testValues.count - 2 == index { viewModel.fetch() } } } } } else { Text("tesetsetsetsettse") } } .onAppear { viewModel.fetch() } .refreshable { viewModel.refresh() } } } struct test: View { let index: Int let data: String @ObservedObject var viewModel: ViewModel var body: some View { VStack(spacing: 8) { test1(index: index, data: data, viewModel: viewModel) Text("------------------------") } } } struct test1: View { let index: Int let data: String @ObservedObject var viewModel: ViewModel var body: some View { VStack { Text(viewModel.testValues[index]) .font(.system(size: 12)) .foregroundStyle(Color.red) .padding(.horizontal, 40) .padding(.vertical, 50) .background { RoundedRectangle(cornerRadius: 20) .fill(Color.blue) } } } } class ViewModel: ObservableObject { @Published var isLoading = false @Published var testValues: [String] = [] func fetch() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.testValues += [ UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, ] } } func refresh() { testValues = [] fetch() } }
Posted
by HansolEom.
Last updated
.
Post not yet marked as solved
7 Replies
3.1k Views
The Build for Previews builds all my targets including the test targets. Is there a way to configure the relevant targets? I do not see an option in the schema editor, and disabling Find Implicit Dependencies has no effect either.
Posted
by chkpnt.
Last updated
.
Post not yet marked as solved
1 Replies
63 Views
Hey all, I have a very simple view that offsets some view based on the value of a binding. To calculate that offset, I also need to have the previous value of the binding. To have that, am using withAnimation(). I am also using a custom animation. To keep things simple, my custom animation right now is just a linear progression. I added some code to keep track of the number of times animate<>(:::) gets called. Turns out, when I add .background(Color.green) to my Text(), the number of calls gets increased by 60 (per second of animation). If .background(Color.green) gets added last (more precisely, after .offset(x: newOffset)), the background is not animated and the extra calls do not happen. After reading the documentation and watching 'Demystifying SwiftUI', 'Demystifying SwiftUI performance' and various general SwiftUI and SwiftUI animation related WWDC sessions I am still feeling like I miss some basic understanding of SwiftUI animations. Who can explain to me what is happening here and why? Or is the fact that animate<>(:::) gets called a number of times that is increasing linearly with the number of modifiers and number of subviews OK, and I should not be worried at all? Relevant code below: View: struct TestView: View { @Binding var offset: Double @State private var previousOffset: Double = 0 @State private var isAnimatingToNewOffset = false private let valuesInView = 20 var body: some View { GeometryReader { geometry in let headingHeight: CGFloat = 80 let newOffset = isAnimatingToNewOffset ? -(offset - previousOffset) / CGFloat(valuesInView) * geometry.size.width : 0 Text("Some text") .frame(width: geometry.size.width) .frame(height: headingHeight) .offset(y: (geometry.size.height - headingHeight) / 2) .background(Color.green) // moving this around, or removing it will cause the animate<>(:::) to be called a different number if times .offset(x: newOffset) } .background(Color.gray) .onChange(of: offset) { (oldValue, newValue) in /// entering an animated change isAnimatingToNewOffset = true withAnimation(Animation(MyAnimation(duration: 1))) { // before updating, keep the value of the current offset previousOffset = offSet } completion: { // now update the previous offset to be ready for a new animation previousOffset = offset // trigger another update of the body, but now without animation isAnimatingToNewOffset = false } } } } My custom animation: struct MyAnimation: CustomAnimation { /// just for debugging to understand how often this method gets called private static var count = 0 let duration: TimeInterval func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic { let relativeProgress = CGFloat(time / duration) // print out the number of times this function is called, and with what value print("\(String(format: "%02i", MyAnimation.count)) - \(String(format: "%1.2f", relativeProgress))") MyAnimation.count += 1 guard time < duration else { return nil } // keeping things simple for now, returning linear progress return value.scaled(by: relativeProgress) } }
Posted
by Joride.
Last updated
.
Post not yet marked as solved
1 Replies
94 Views
Hey folks, Having some trouble getting Animations to behave properly. I'll try to explain what I am doing, but maybe it is easier to run the project, which you can clone from github here. The key is in commenting out line 32/33 and uncommenting lines 34/35 in GaugeView.swift Otherwise: here is the high-level goal I'm aiming for: I'd like to see a horizontal gauge, akin to a tape measure (ignore the colors in this example image ), but (initially) centered on zero, and extending both to negative and positive measures. It will represent some value and that value can go up to a positive maximum number, and a minimum negative number. On overflow on either side, the tape measure should wrap-around. For this, I would like to create the illusion of an infinite tape measure, that keeps moving as the values change. There will be NO user interaction at all, the values are coming in from some device, and simply need to be displayed. Now, the basic logic seems to work: There is a tapemeasure view, which shows zero in the center. As a new value comes in, the view's offset gets animated to have the new value be in the center. At the end of the animation. The view's offset is reset to zero (without animation), and the view's content is updated to reflect the new center value. In the current project there is only a single view, but the idea it that to the left and right of the visible view, there will be two other views to fill in the other parts. However, that is not relevant at the moment. To support changes mid-animation, I've implemented a basic custom animation myself. This one allows me to measure how often animate<>(:::) gets called for now, but will be needed to make sure animations remain smooth when merging them. The issue I run into is that that view with the actual contant contains a ForEach. And because of that, animate<>(:::) seems to be called many more times than I would expect. That number seems to be linearly related to the number of items in the ForEach. So I watched the WWDC session on view identy (Demystify SwiftUI), watched all animation-related sessions and tried to find some documatation on animations. Couldn't find what I was looking for. When I replace the content view with a Rectangle(), the issue disappears. So my question is: how to prevent a subview's changes to call animate(:::) so many times when a ForEach is present? Or maybe just block all internal animations of a subview? In essence I never need the content of the subview to be animated, only it's offset in the superview.
Posted
by Joride.
Last updated
.
Post not yet marked as solved
0 Replies
75 Views
I am trying to present a GroupActivitySharingController using SwiftUI. I am using a NSViewControllerRepresentable: @State var event : Event func makeNSViewController(context: NSViewControllerRepresentableContext<MeetingGroupActivitySharingRepresentableView>) -> GroupActivitySharingController { return try! GroupActivitySharingController(MeetingGroupActivity(event: event)) } func updateNSViewController(_ nsViewController: GroupActivitySharingController , context: NSViewControllerRepresentableContext<MeetingGroupActivitySharingRepresentableView>) { print("Updating VC") } } I present it as following : .sheet(isPresented: $showGroupActivitySharingView) { MeetingGroupActivitySharingRepresentableView(event: observedEvent.event) } It works fine on iOS, however on MacOS, I cannot dismiss the view. I see the following error: dismissViewController:: Error: maybe this view controller was not presented? ( 0 CoreFoundation 0x000000019d75accc __exceptionPreprocess + 176 1 libobjc.A.dylib 0x000000019d242788 objc_exception_throw + 60 2 Foundation 0x000000019e8cbc6c -[NSCalendarDate initWithCoder:] + 0 3 AppKit 0x00000001a145a77c -[NSViewController dismissViewController:] + 224 4 _GroupActivities_AppKit 0x0000000232d65cf0 $s23_GroupActivities_AppKit0A25ActivitySharingControllerC011dismissViewG06resultyAA0aeF6ResultO_tFyyYaYbScMYccfU_TY0_ + 444 5 _GroupActivities_AppKit 0x0000000232d67b65 $s23_GroupActivities_AppKit0A25ActivitySharingControllerC011dismissViewG06resultyAA0aeF6ResultO_tFyyYaYbScMYccfU_TATQ0_ + 1 6 _GroupActivities_AppKit 0x0000000232d68bd9 $sIeghH_ytIeghHr_TRTQ0_ + 1 7 _GroupActivities_AppKit 0x0000000232d68bdd $sIeghH_ytIeghHr_TRTATQ0_ + 1 8 _GroupActivities_AppKit 0x0000000232d66931 $sxIeghHr_xs5Error_pIegHrzo_s8SendableRzs5NeverORs_r0_lTRyt_Tg5TQ0_ + 1 9 _GroupActivities_AppKit 0x0000000232d68ba5 $sxIeghHr_xs5Error_pIegHrzo_s8SendableRzs5NeverORs_r0_lTRyt_Tg5TATQ0_ + 1 10 libswift_Concurrency.dylib 0x0000000263cfb0f9 _ZL23completeTaskWithClosurePN5swift12AsyncContextEPNS_10SwiftErrorE + 1 ) Any idea what is going on?
Posted
by girishw.
Last updated
.
Post not yet marked as solved
0 Replies
78 Views
Hello everyone! I recently started to think to introduce in my app SplitView for iPads instead of TabView which I currently have. But I would like to keep the TabView for iPhone and compact size class of iPad. I took my inspiration from a lot of Apple apps, like Apple Music or Photos. I was also looking at the Fruta app where similar technique is implemented, but that particular implementation does not fit my needs. The problem I’m having is that every time SplitView changes to TabView or vise versa the whole state of the app resets. I tried everything I could imagine, I couldn’t find a way to overcome this issue. The only thing I was able to fix is to maintain the same tab/list item selection, but everything else resets. Could anybody help me to resolve this issue? Thanks!
Posted Last updated
.
Post marked as solved
1 Replies
98 Views
Everything works as expected until I add the paging behavior to the scrollView with a non-zero content margin. The paging behavior ends up not being centered on the cards. Here is a simple example: import SwiftUI struct CarouselView: View { var body: some View { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 0) { ForEach(0 ..< 5, id: \.self) { _ in RoundedRectangle(cornerRadius: 25) .fill(.ultraThinMaterial) .containerRelativeFrame(.horizontal) .scrollTransition(axis: .horizontal, transition: { content, phase in content .scaleEffect(x: phase.isIdentity ? 1 : 0.8, y: phase.isIdentity ? 1 : 0.8) }) } } .scrollTargetLayout() } .scrollTargetBehavior(.paging) .contentMargins(60) // NOTE: I want to see the sides of the next and previous card .background(Gradient(colors: [.purple, .red])) } } Thanks!
Posted
by zacswolf.
Last updated
.