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

Posts under SwiftUI tag

200 Posts

Post

Replies

Boosts

Views

Activity

SwiftData & CloudKit: Arrays of Codable Structs Causing NSKeyedUnarchiveFromData Error
I have SwiftData models containing arrays of Codable structs that worked fine before adding CloudKit capability. I believe they are the reason I started seeing errors after enabling CloudKit. Example model: @Model final class ProtocolMedication { var times: [SchedulingTime] = [] // SchedulingTime is Codable // other properties... } After enabling CloudKit, I get this error logged to the console: 'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release CloudKit Console shows this times data as "plain text" instead of "bplist" format. Other struct/enum properties display correctly (I think) as "bplist" in CloudKit Console. The local SwiftData storage handled these arrays fine - this issue only appeared with CloudKit integration. What's the recommended approach for storing arrays of Codable structs in SwiftData models that sync with CloudKit?
8
1
501
12h
SwiftUI .task does not update its references on view update
I have this sample code import SwiftUI struct ContentView: View { var body: some View { ParentView() } } struct ParentView: View { @State var id = 0 var body: some View { VStack { Button { id+=1 } label: { Text("update id by 1") } TestView(id: id) } } } struct TestView: View { var sequence = DoubleGenerator() let id: Int var body: some View { VStack { Button { sequence.next() } label: { Text("print next number").background(content: { Color.green }) } Text("current id is \(id)") }.task { for await number in sequence.stream { print("next number is \(number)") } } } } final class DoubleGenerator { private var current = 1 private let continuation: AsyncStream<Int>.Continuation let stream: AsyncStream<Int> init() { var cont: AsyncStream<Int>.Continuation! self.stream = AsyncStream { cont = $0 } self.continuation = cont } func next() { guard current >= 0 else { continuation.finish() return } continuation.yield(current) current &*= 2 } } the print statement is only ever executed if I don't click on the update id by 1 button. If i click on that button, and then hit the print next number button, the print statement doesn't print in the xcode console. I'm thinking it is because the change in id triggered the view's init function to be called, resetting the sequence property and so subsequent clicks to the print next number button is triggering the new version of sequence but the task is still referring its previous version. Is this expected behaviour? Why in onChange and Button, the reference to the properties is always up to date but in .task it is not?
1
0
70
13h
NSHostingView stops receiving mouse events when layered above another NSHostingView (macOS Tahoe 26.2)
I’m running into a problem with SwiftUI/AppKit event handling on macOS Tahoe 26.2. I have a layered view setup: Bottom: AppKit NSView (NSViewRepresentable) Middle: SwiftUI view in an NSHostingView with drag/tap gestures Top: Another SwiftUI view in an NSHostingView On macOS 26.2, the middle NSHostingView no longer receives mouse or drag events when the top NSHostingView is present. Events pass through to the AppKit view below. Removing the top layer immediately restores interaction. Everything works correctly on macOS Sequoia. I’ve posted a full reproducible example and detailed explanation on Stack Overflow, including a single-file demo: Stack Overflow post: https://stackoverflow.com/q/79862332 I also found a related older discussion here, but couldn’t get the suggested workaround to apply: https://developer.apple.com/forums/thread/759081 Any guidance would be appreciated. Thanks!
4
0
311
1d
Animation does not work with List, while works with ScrollView + ForEach
Why there is a working animation with ScrollView + ForEach of items removal, but there is none with List? ScrollView + ForEach: struct ContentView: View { @State var items: [String] = Array(1...5).map(\.description) var body: some View { ScrollView(.vertical) { ForEach(items, id: \.self) { item in Text(String(item)) .frame(maxWidth: .infinity, minHeight: 50) .background(.gray) .onTapGesture { withAnimation(.linear(duration: 0.1)) { items = items.filter { $0 != item } } } } } } } List: struct ContentView: View { @State var items: [String] = Array(1...5).map(\.description) var body: some View { List(items, id: \.self) { item in Text(String(item)) .frame(maxWidth: .infinity, minHeight: 50) .background(.gray) .onTapGesture { withAnimation(.linear(duration: 0.1)) { items = items.filter { $0 != item } } } } } }```
5
0
109
1d
SwiftUI menu not resizing images
I failed to resize the icon image from instances of NSRunningApplication. I can only get 32×32 while I'm expecting 16×16. I felt it unintuitive in first minutes… Then I figured out that macOS menu seems not allowing many UI customizations (for stability?), especially in SwiftUI. What would be my best solution in SwiftUI? Must I write some boilerplate SwiftUI-AppKit bridging?
1
0
64
1d
WWDC21 Demystify SwiftUI question
When the guy was talking about structural identity, starting at about 8:53, he mentioned how the swiftui needs to guarantee that the two views can't swap places, and it does this by looking at the views type structure. It guarantees that the true view will always be an A, and the false view will always be a B. Not sure exactly what he means because views can't "swap places" like dogs. Why isn't just knowing that some View is shown in true, and another is shown in false, enough for its identity? e.g. The identity could be "The view on true" vs "The view on false", same as his example with "The dog on the left" vs "The dog on the right"
0
0
40
1d
hapticpatternlibrary.plist error with Text entry fields in Simulator only
When I have a TextField or TextEditor, tapping into it produces these two console entries about 18 times each: CHHapticPattern.mm:487 +[CHHapticPattern patternForKey:error:]: Failed to read pattern library data: Error Domain=NSCocoaErrorDomain Code=260 "The file “hapticpatternlibrary.plist” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSURL=file:///Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSUnderlyingError=0x600000ca1b30 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} <_UIKBFeedbackGenerator: 0x600003505290>: Error creating CHHapticPattern: Error Domain=NSCocoaErrorDomain Code=260 "The file “hapticpatternlibrary.plist” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSURL=file:///Library/Audio/Tunings/Generic/Haptics/Library/hapticpatternlibrary.plist, NSUnderlyingError=0x600000ca1b30 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} My app does not use haptics. This doesn't appear to cause any issues, although entering text can feel a bit sluggish (even on device), but I am unable to determine relatedness. None-the-less, it definitely is a lot of log noise. Code to reproduce in simulator (xcode 26.2; ios 26 or 18, with iPhone 16 Pro or iPhone 17 Pro): import SwiftUI struct ContentView: View { @State private var textEntered: String = "" @State private var textEntered2: String = "" @State private var textEntered3: String = "" var body: some View { VStack { Spacer() TextField("Tap Here", text: $textEntered) TextField("Tap Here Too", text: $textEntered2) TextEditor(text: $textEntered3) .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.primary, lineWidth: 1)) .frame(height: 100) Spacer() } } } #Preview { ContentView() } Tapping back and forth in these fields generates the errors each time. Thanks, Steve
2
0
105
1d
How to animate `UIHostingController.view` frame when my View's size changes?
I have a UIHostingController on which I have set: hostingController.sizingOptions = [.intrinsicContentSize] The size of my SwiftUI content changes with animation (I update a @Published property on an ObservableObject inside a withAnimation block). However, I notice that my hostingController.view just jumps to the new frame without animating the change. Question: how can I animate the frame changes in UIHostingController that are caused by sizingOptions = [.intrinsicContentSize]
1
0
40
1d
Text with .secondary vanishes when Material background is clipped to UnevenRoundedRectangle in ScrollView
I just found a weird bug: If you place a Text view using .foregroundStyle(.secondary), .tertiary, or other semantic colors inside a ScrollView, and apply a Material background clipped to an UnevenRoundedRectangle, the text becomes invisible. This issue does not occur when: The text uses .primary or explicit colors (e.g., .red, Color.blue), or The background is clipped to a standard shape (e.g., RoundedRectangle). A minimal reproducible example is shown below: ScrollView{ VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello World.") .font(.system(size: 15)) .foregroundStyle(.quinary) } } .padding() .frame(height: 100) .background(Material.regular) .clipShape(UnevenRoundedRectangle(topLeadingRadius: 10,bottomLeadingRadius: 8,bottomTrailingRadius:8, topTrailingRadius: 8))
0
0
73
2d
Tabview page dots like in the weather app
Hi, I am looking to display (in SwiftUI) the Tabview page dots like in the weather app in the toolbar, an important thing is I want to keep page controls by tapping and scrubbing. Actually, I want to do what's on Apple Design's Page Controls page; here's the link and a photo of what I'd like to do. Could you help me? https://developer.apple.com/design/human-interface-guidelines/page-controls
1
0
36
2d
Why MapKit Is So Unpredictable for macOS?
I have an existing iOS app with MapKit. It always shows the current user location with UserAnnotation. But the same isn't true for macOS. I have this sample macOS application in SwiftUI. In the following, the current user location with a large blue dot appears only occasionally. It won't, 19 of 20 times. Why is that? I do have a location privacy key in Info.plist. And the Location checkbox is on under Signing & Capabilities. import SwiftUI import MapKit struct ContentView: View { @State private var markerItems: [MarkerItem] = [ MarkerItem(name: "Farmers Market 1", lat: 35.681, lon: 139.691), MarkerItem(name: "Farmers Market 2", lat: 35.685, lon: 139.695), MarkerItem(name: "Farmers Market 3", lat: 35.689, lon: 139.699) ] @State private var position: MapCameraPosition = .automatic var body: some View { Map(position: $position) { UserAnnotation() ForEach(markerItems, id: \.self) { item in Marker(item.name, coordinate: CLLocationCoordinate2D(latitude: item.lat, longitude: item.lon)) } } .mapControlVisibility(.hidden) .mapStyle(.standard(elevation: .realistic)) .ignoresSafeArea() } } #Preview { ContentView() } struct MarkerItem: Hashable { let name: String let lat: Double let lon: Double }
0
0
18
2d
Zoom navigation transitions for tabViewBottomAccessory are not working in SwiftUI with ObservableObject or Observable
The zoom navigation transition with matchedTransitionSource in tabViewBottomAccessory does not work when a Published var in an ObservableObjector Observable gets changed. Here is an minimal reproducible example with ObservableObject: import SwiftUI import Combine private final class ViewModel: ObservableObject { @Published var isPresented = false } struct ContentView: View { @Namespace private var namespace @StateObject private var viewModel = ViewModel() // @State private var isPresented = false var body: some View { TabView { Button { viewModel.isPresented = true } label: { Text("Start") } .tabItem { Image(systemName: "house") Text("Home") } Text("Search") .tabItem { Image(systemName: "magnifyingglass") Text("Search") } Text("Profile") .tabItem { Image(systemName: "person") Text("Profile") } } .sheet(isPresented: $viewModel.isPresented) { Text("Sheet") .presentationDragIndicator(.visible) .navigationTransition(.zoom(sourceID: "tabViewBottomAccessoryTransition", in: namespace)) } .tabViewBottomAccessory { Button { viewModel.isPresented = true } label: { Text("BottomAccessory") } .matchedTransitionSource(id: "tabViewBottomAccessoryTransition", in: namespace) } } } However, when using only a State property everything works: import SwiftUI import Combine private final class ViewModel: ObservableObject { @Published var isPresented = false } struct ContentView: View { @Namespace private var namespace // @StateObject private var viewModel = ViewModel() @State private var isPresented = false var body: some View { TabView { Button { isPresented = true } label: { Text("Start") } .tabItem { Image(systemName: "house") Text("Home") } Text("Search") .tabItem { Image(systemName: "magnifyingglass") Text("Search") } Text("Profile") .tabItem { Image(systemName: "person") Text("Profile") } } .sheet(isPresented: $isPresented) { Text("Sheet") .presentationDragIndicator(.visible) .navigationTransition(.zoom(sourceID: "tabViewBottomAccessoryTransition", in: namespace)) } .tabViewBottomAccessory { Button { isPresented = true } label: { Text("BottomAccessory") } .matchedTransitionSource(id: "tabViewBottomAccessoryTransition", in: namespace) } } }
3
0
205
2d
onWorldRecenter memory leak and duplicate callbacks in ImmersiveSpace
Posting this here in case this information is helpful to other developers: As of visionOS 26.3 beta 1, onWorldRecenter has two significant issues: (FB21557639) Memory Leak: When onWorldRecenter is assigned to a RealityView within an ImmersiveSpace, it appears to retain a strong reference to the view's internal SwiftUI context. When the immersive space is dismissed, the view's @State objects will not be deallocated. Also, each time the immersive space view's body is executed, additional state storage will be allocated and leaked. Multiple Callbacks: When the user long-presses the Digital Crown, the onWorldRecenter closure will be called multiple times, once for each past view body execution, including those of immersive space views that have been previously dismissed. Although these issues seem to be most prevalent when onWorldRecenter is used with an ImmersiveSpace, they may also occur in the context of a WindowGroup under certain circumstances. It's possible to work around this problem by moving onWorldRecenter to an empty overlay view within the app's primary WindowGroup and forwarding the world recenter events to ImmersiveSpace views through a notification system, coupled with a debouncer as an extra precaution.
1
0
785
2d
tabViewBottomAccessory in 26.1: View's @State is lost when switching tabs
Any view that is content for the tabViewBottomAccessory API fails to retain its state as of the last couple of 26.1 betas (and RC). The loss of state happens (at least) when the currently selected tab is switched (filed as FB20901325). Here's code to reproduce the issue: struct ContentView: View { @State private var selectedTab = TabSelection.one enum TabSelection: Hashable { case one, two } var body: some View { TabView(selection: $selectedTab) { Tab("One", systemImage: "1.circle", value: .one) { BugExplanationView() } Tab("Two", systemImage: "2.circle", value: .two) { BugExplanationView() } } .tabViewBottomAccessory { AccessoryView() } } } struct AccessoryView: View { @State private var counter = 0 // This guy's state gets lost (as of iOS 26.1) var body: some View { Stepper("Counter: \(counter)", value: $counter) .padding(.horizontal) } } struct BugExplanationView: View { var body: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { Text("(1) Manipulate the counter state") Text("(2) Then switch tabs") Text("BUG: The counter state gets unexpectedly reset!") } .multilineTextAlignment(.leading) } } }
5
4
479
2d
tabViewBottomAccessory causes unstable view identity for views accessing Environment or State
Views placed inside tabViewBottomAccessory that access @Environment values or contain @State properties experience unstable identity, as shown by Self._printChanges(). The identity changes on every structural update to the TabView, even though the view's actual identity should remain stable. This causes unnecessary view recreation and breaks SwiftUI's expected identity and lifecycle behavior. Environment Xcode Version 26.2 (17C52) iOS 26.2 simulator and device struct ContentView: View { @State var showMoreTabs = true struct DemoTab: View { var body: some View { Text(String(describing: type(of: self))) } } var body: some View { TabView { Tab("Home", systemImage: "house") { DemoTab() } Tab("Alerts", systemImage: "bell") { DemoTab() } if showMoreTabs { TabSection("Categories") { Tab("Climate", systemImage: "fan") { DemoTab() } Tab("Lights", systemImage: "lightbulb") { DemoTab() } } } Tab("Settings", systemImage: "gear") { List { Toggle("Show more Tabs", isOn: $showMoreTabs) } } } .tabViewBottomAccessory { AccessoryView() } .task { while true { try? await Task.sleep(for: .seconds(5)) if Task.isCancelled { break } print("toggling showMoreTabs") showMoreTabs.toggle() } } .tabBarMinimizeBehavior(.onScrollDown) } } struct AccessoryView: View { var body: some View { HStack { EnvironmentAccess() WithState() Stateless() } } } struct EnvironmentAccess: View { @Environment(\.tabViewBottomAccessoryPlacement) var placement var body: some View { // FIXME: EnvironmentAccess: @self, @identity, _placement changed. // Identity should be stable let _ = Self._printChanges() Text(String(describing: type(of: self))) } } struct WithState: View { @State var int = Int.random(in: 0...100) var body: some View { // FIXME: WithState: @self, @identity, _id changed. // Identity should be stable let _ = Self._printChanges() Text(String(describing: type(of: self))) } } struct Stateless: View { var body: some View { // Works as expected: Stateless: @self changed. let _ = Self._printChanges() Text(String(describing: type(of: self))) } } This bug seems to make accessing TabViewBottomAccessoryPlacement impossible without losing view identity; the demo code is affected by the bug. Accessing a value like @Environment(\.colorScheme) is similarly affected, making visually adapting the contents of the accessory to the TabView content without losing identity challenging if not impossible. Submitted as FB21627918.
0
0
22
2d
AsyncImage - Cancelled Loading before View is Visible
I have been playing around with the new AsyncImage Api in SwiftUI I am using the initialiser that passes in a closure with the AsyncImagePhase, to view why an image may not load, when I looked at the error that is passed in if the phase is failure, the localised description of the error is "Cancelled" but this is happening before the view is being displayed. I am loading these images in a list, I imagine I am probably doing something which is causing the system to decide to cancel the loading, but I cannot see what. Are there any tips to investigate this further?
16
8
13k
2d
Performance in Large Datasets (SwiftUI+SwiftData app)
Hi everyone, In the simple app below, I have a QueryView that has LazyVStack containing 100k TextField's that edit the item's content. The items are fetched with a @Query. On launch, the app will generate 100k items. Once created, when I press any of the TextField's , a severe hang happens, and every time I type a single character, it will cause another hang over and over again. I looked at it in Instruments and it shows that the main thread is busy during the duration of the hang (2.31 seconds) updating QueryView. From the cause and effect graph, the update is caused by @Observable QueryController <Item>.(Bool). Why does it take too long to recalculate the view, given that it's in a LazyVStack? (In other words, why is the hang duration directly proportional to the number of items?) How to fix the performance of this app? I thought adding LazyVStack was all I need to handle the large dataset, but maybe I need to add a custom pagination with .fetchLimit on top of that? (I understand that ModelActor would be an alternative to @Query because it will make the database operations happen outside of the main thread which will fix this problem, but with that I will lose the automatic fetching of @Query.) Thank you for the help! import SwiftData import SwiftUI @main struct QueryPerformanceApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: [Item.self], inMemory: true) } } } @Model final class Item { var name: String init(name: String) { self.name = name } } struct ItemDetail: View { @Bindable var item: Item var body: some View { TextField("Name", text: $item.name) } } struct QueryView: View { @Query private var items: [Item] var body: some View { ScrollView { LazyVStack { ForEach(items) { item in VStack { ItemDetail(item: item) } } } } } } struct ContentView: View { let itemCount = 100_000 @Environment(\.modelContext) private var context @State private var isLoading = true var body: some View { Group { if isLoading { VStack(spacing: 16) { ProgressView() Text("Generating \(itemCount) items...") } } else { QueryView() } } .task { for i in 1...itemCount { context.insert(Item(name: "Item \(i)")) } try? context.save() isLoading = false } } }
1
0
97
3d
`ImageRenderer.render` halts program with `EXC_BREAKPOINT` inside SwiftUI/AttributeGraph
This extension View { public func renderSomething() async throws { let renderer = ImageRenderer(content: self) // renderer.colorMode = .linear renderer.render { size, context in print(size) // ... } // ... } } let view: some View = ... view.renderSomething() // → exception will cause the program to exit with EXC_BREAKPOINT deep inside SwiftUI. This worked with previous versions of Xcode, SwiftUI, and macOS. Xcode Version 26.2 (17C52), macOS Sequoia 15.7.3, using toolchain bundled with Xcode.
0
0
14
3d
Bug: Xcode 26.2 wants `ENABLE_DEBUG_DYLIB`: How do I enable that in `Package.swift`?
Xcode tells me Previewing in executable targets now requires a new build layout for unoptimized builds. Either set ENABLE_DEBUG_DYLIB to YES for this target, or break out your preview code into a separate framework with its own scheme. How do enable that in Package.swift. swiftSettings don't work (.define and unsafeFlags with -D ...). Creating a library product that the executable then depends on doesn't help either. I have two targets, one is an executable target. The #Preview macro is in the non-executable target.
1
0
27
3d