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

Instruments Crash using swiftui instrument
Instruments is crashing when the swiftui instrument is stopped (the session is finished) and the transfer begins from device to device: Crashed Thread: 11 Dispatch queue: com.apple.swiftuitracingsupport.reading Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4 Terminating Process: exc handler [1633] I've tried removing derived data, reinstalling xcode, updating xcode (I originally thought this might be the issue -- I needed to update to 26.2 from the 26 RC -- the update didn't fix crash or change the crash report), and restarting both devices. I'm running Instruments/Xcode 26.2 on a MacBook Pro 15" (2018) running Mac OS 15.7.2 (24G325) with an iPhone 16 Pro Max running 26.2. Hoping someone else might have seen this or could help me troubleshoot. I find the swiftui instrument be helpful and like to use it :) I can post a complete crash report as well.
5
0
202
15h
ScrollView hicjacking focus in swiftui
Greetings! I'm facing a problem handleling full keyboard access in my app. This is a simpler version of the code: struct PrimerTest: View { @FocusState private var focusedImage: Int? var body: some View { VStack(alignment: .leading, spacing: 20) { Link("Go to google or smth", destination: URL(string: "https://google.com")!) .font(.headline) Text("First text") Text("Second text") HStack { Text("Label") .accessibilityHidden(true) Spacer() Button("Play") { print("Im a button") } } Text("Selecciona un perfil con el teclado (Tab):") .font(.caption) .foregroundColor(.secondary) HStack { ForEach(0..<5, id: \.self) { index in Image(systemName: "person.circle.fill") .resizable() .frame(width: 30, height: 30) .focusable(true) .focused($focusedImage, equals: index) .foregroundStyle(focusedImage == index ? Color.blue : Color.gray) .scaleEffect(focusedImage == index ? 1.2 : 1.0) .animation(.easeInOut, value: focusedImage) .accessibilityHidden(true) } } } .navigationTitle("Title n stuff") .padding() } } And the focus behaves as expected and the important thing, we can access que button on the right side of the screen But as soon as we introduce the scrollview, the right side button is unaccessible, since when we hit tab we go back to the back button in the nav stack header. struct PrimerTest: View { @FocusState private var focusedImage: Int? var body: some View { ScrollView { VStack(alignment: .leading, spacing: 20) { Link("Go to google or smth", destination: URL(string: "https://google.com")!) .font(.headline) Text("First text") Text("Second text") HStack { Text("Label") .accessibilityHidden(true) Spacer() Button("Play") { print("Im a button") } } Text("Selecciona un perfil con el teclado (Tab):") .font(.caption) .foregroundColor(.secondary) HStack { ForEach(0..<5, id: \.self) { index in Image(systemName: "person.circle.fill") .resizable() .frame(width: 30, height: 30) .focusable(true) .focused($focusedImage, equals: index) .foregroundStyle(focusedImage == index ? Color.blue : Color.gray) .scaleEffect(focusedImage == index ? 1.2 : 1.0) .animation(.easeInOut, value: focusedImage) .accessibilityHidden(true) } } } } .navigationTitle("Title n stuff") .padding() } } I've tried all the things I found online and none achieves an acceptable behavoir, I've seen ppl saying this issue has been fixed in ipados with the focusSection modifier, but I have not seen any fix fot this issue in ios.
0
0
106
18h
ShareLink "Save Image" action dismisses presenting view after saving
When using ShareLink in SwiftUI to share an image, the “Save Image” action dismisses not only the share sheet but also the presenting SwiftUI view. The behavior differs depending on whether the photo library permission alert appears. Observed behavior: The first time the user taps Save Image, the system permission alert appears. After granting permission, the image saves successfully and the share sheet dismisses normally. On subsequent attempts, the image is saved successfully, but both the share sheet and the presenting view are dismissed unexpectedly. Expected behavior: After saving the image, only the share sheet should dismiss. The presenting SwiftUI view should remain visible. Steps to Reproduce Present a SwiftUI view using .sheet. Inside that view, add a ShareLink configured to export a PNG image using Transferable. Tap the ShareLink button. Choose Save Image. Grant permission the first time (if prompted). Repeat the action. Result: On subsequent saves, the share sheet dismisses and the presenting view is dismissed as well. Sample code ` internal import System import UniformTypeIdentifiers import SwiftUI struct RootView: View { @State private var isPresented: Bool = false var body: some View { ZStack { Color.white Button("Show parent view") { isPresented = true } } .sheet(isPresented: $isPresented) { ParentView() } } } struct ParentView: View { @State private var isPresented: Bool = false var body: some View { NavigationStack { ZStack { Color.red.opacity(0.5) } .toolbar { ToolbarItem() { let name = "\(UUID().uuidString)" let image = UIImage(named: "after")! return ShareLink( item: ShareableImage(image: image, fileName: name), preview: SharePreview( name, image: Image(uiImage: image) ) ) { Image(uiImage: UIImage(resource: .Icons.share24)) .resizable() .foregroundStyle(Color.black) .frame(width: 24, height: 24) } } } } } } struct ShareableImage: Transferable { let image: UIImage let fileName: String static var transferRepresentation: some TransferRepresentation { FileRepresentation(exportedContentType: .png) { item in let fileURL = FileManager.default.temporaryDirectory .appendingPathComponent(item.fileName) .appendingPathExtension("png") guard let data = item.image.pngData() else { throw NSError(domain: "ImageEncodingError", code: 0) } try data.write(to: fileURL) return SentTransferredFile(fileURL) } } } `
0
0
20
18h
ShareLink "save Image" action dismiss parent view
ShareLink works fine except for save image action which dismiss the presenting view first time system shows the premission alert so image get saved without any problem but for the next saves image get saved then share sheet dismiss and also presenting view dismiss as well here is a sample code ` internal import System import UniformTypeIdentifiers import SwiftUI struct RootView: View { @State private var isPresented: Bool = false var body: some View { ZStack { Color.white Button("Show parent view") { isPresented = true } } .sheet(isPresented: $isPresented) { ParentView() } } } struct ParentView: View { @State private var isPresented: Bool = false var body: some View { NavigationStack { ZStack { Color.red.opacity(0.5) } .toolbar { ToolbarItem() { let name = "\(UUID().uuidString)" let image = UIImage(named: "after")! return ShareLink( item: ShareableImage(image: image, fileName: name), preview: SharePreview( name, image: Image(uiImage: image) ) ) { Image(uiImage: UIImage(resource: .Icons.share24)) .resizable() .foregroundStyle(Color.black) .frame(width: 24, height: 24) } } } } } } struct ShareableImage: Transferable { let image: UIImage let fileName: String static var transferRepresentation: some TransferRepresentation { FileRepresentation(exportedContentType: .png) { item in let fileURL = FileManager.default.temporaryDirectory .appendingPathComponent(item.fileName) .appendingPathExtension("png") guard let data = item.image.pngData() else { throw NSError(domain: "ImageEncodingError", code: 0) } try data.write(to: fileURL) return SentTransferredFile(fileURL) } } } `
0
0
29
18h
iOS 26+ UITabBar unselected item colors not updating with UITabBarAppearance
I'm using UITabBarAppearance to customize my TabBar in a SwiftUI app. The customization works perfectly on iOS 18 and earlier, but after updating to iOS 26, the unselected tab items no longer respect my color settings - they just appear black (they are on a white background).Here's my simplified setup: struct ContentView: View { var body: some View { TabView { Text("Home") .tabItem { Image(systemName: "house") Text("Home") } .tag(0) Text("Settings") .tabItem { Image(systemName: "gear") Text("Settings") } .tag(1) } .onAppear { setupTabBarAppearance() } } private func setupTabBarAppearance() { let appearance = UITabBarAppearance() appearance.configureWithOpaqueBackground() let itemAppearance = UITabBarItemAppearance() // These settings work for selected items itemAppearance.selected.iconColor = .systemBlue itemAppearance.selected.titleTextAttributes = [ .font: UIFont.systemFont(ofSize: 10), .foregroundColor: UIColor.systemBlue ] // These settings STOPPED working on iOS 26 for unselected items itemAppearance.normal.iconColor = .gray itemAppearance.normal.titleTextAttributes = [ .font: UIFont.systemFont(ofSize: 10), .foregroundColor: UIColor.gray ] appearance.stackedLayoutAppearance = itemAppearance appearance.inlineLayoutAppearance = itemAppearance appearance.compactInlineLayoutAppearance = itemAppearance UITabBar.appearance().standardAppearance = appearance UITabBar.appearance().scrollEdgeAppearance = appearance } }
0
0
38
18h
Crown Sequencer warning on Scroll
I have a Form (scrollable) that contains 2 inputs as a Picker and a Stepper where frequency is an enum and time an Int. struct ConfigurationView: View { @Bindable var configuration: ConfigurationModel var body: some View { NavigationStack { Form { Picker(.frequency, selection: $configuration.frequency) { /* ... */ } Stepper(value: $configuration.time, in: 1...8) { // Stepper Label } .focusable() Button(.save) { configuration.save() } .buttonStyle(.borderedProminent) .listRowBackground(Color.clear) } .navigationTitle(.configuration) } } } The main issue I'm facing is a delay in the UI (1-3 seconds) while interacting with the Digital Crown over the focused Stepper which prints a Crown Sequencer warning: Crown Sequencer was set up without a view property. This will inevitably lead to incorrect crown indicator states This mainly happens when the Picker, which is showed as a modal or Sheet, changes its value, so the Stepper no longer gets focusable again. Looking into the docs, lectures and WWDC videos I just found that we need to provide a some sort of a focus, that's why the Stepper control has a focusable() modifier. I don't know if there is an overlap between the scroll and the focus event on the control.
0
0
34
1d
Wrong position of searchable component on first render
Hey all, I found a weird behaviour with the searchable component. I created a custom bottom nav bar (because I have custom design in my app) to switch between screens. On one screen I display a List component with the searchable component. Whenever I enter the search screen the first time, the searchable component is displayed at the bottom. This is wrong. It should be displayed at the top under the navigationTitle. When I enter the screen a second time, everything is correct. This behaviour can be reproduced on all iOS 26 versions on the simulator and on a physical device with debug and release build. On iOS 18 everything works fine. Steps to reproduce: Cold start of the app Click on Search TabBarIcon (searchable wrong location) Click on Home TabBarIcon Click on Search TabBarIcon (searchable correct location) Simple code example: import SwiftUI struct ContentView: View { @State var selectedTab: Page = Page.main var body: some View { NavigationStack { ZStack { VStack { switch selectedTab { case .main: MainView() case .search: SearchView() } } VStack { Spacer() VStack(spacing: 0) { HStack(spacing: 0) { TabBarIcon(iconName: "house", selected: selectedTab == .main, displayName: "Home") .onTapGesture { selectedTab = .main } TabBarIcon(iconName: "magnifyingglass", selected: selectedTab == .search, displayName: "Search") .onTapGesture { selectedTab = .search } } .frame(maxWidth: .infinity) .frame(height: 55) .background(Color.gray) } .ignoresSafeArea(.all, edges: .bottom) } } } } } struct TabBarIcon: View { let iconName: String let selected: Bool let displayName: String var body: some View { ZStack { VStack { Image(systemName: iconName) .resizable() .renderingMode(.template) .aspectRatio(contentMode: .fit) .foregroundColor(Color.black) .frame(width: 22, height: 22) Text(displayName) .font(Font.system(size: 10)) } } .frame(maxWidth: .infinity) } } enum Page { case main case search } struct MainView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() .navigationTitle("Home") } } struct SearchView: View { @State private var searchText = "" let items = [ "Apple", "Banana", "Pear", "Strawberry", "Orange", "Peach", "Grape", "Mango" ] var filteredItems: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.localizedCaseInsensitiveContains(searchText) } } } var body: some View { List(filteredItems, id: \.self) { item in Text(item) } .navigationTitle("Fruits") .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search") } }
3
0
196
2d
Two errors in debug: com.apple.modelcatalog.catalog sync and nw_protocol_instance_set_output_handler
We get two error message in Xcode debug. apple.model.catalog we get 1 time at startup, and the nw_protocol_instance_set_output_handler Not calling remove_input_handler on 0x152ac3c00:udp we get on sartup and some time during running of the app. I have tested cutoff repos WS eg. But nothing helpss, thats for the nw_protocol. We have a fondationmodel in a repo but we check if it is available if not we do not touch it. Please help me? nw_protocol_instance_set_output_handler Not calling remove_input_handler on 0x152ac3c00:udp com.apple.modelcatalog.catalog sync: connection error during call: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.modelcatalog.catalog was invalidated: Connection init failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.modelcatalog.catalog was invalidated: Connection init failed at lookup with error 159 - Sandbox restriction.} reached max num connection attempts: 1 The function we have in the repo is this: public actor FoundationRepo: JobDescriptionChecker, SubskillSuggester { private var session: LanguageModelSession? private let isEnabled: Bool private let shouldUseLocalFoundation: Bool private let baseURLString = "https://xx.xx.xxx/xx" private let http: HTTPPac public init(http: HTTPPac, isEnabled: Bool = true) { self.http = http self.isEnabled = isEnabled self.session = nil guard isEnabled else { self.shouldUseLocalFoundation = false return } let model = SystemLanguageModel.default guard model.supportsLocale() else { self.shouldUseLocalFoundation = false return } switch model.availability { case .available: self.shouldUseLocalFoundation = true case .unavailable(.deviceNotEligible), .unavailable(.appleIntelligenceNotEnabled), .unavailable(.modelNotReady): self.shouldUseLocalFoundation = false @unknown default: self.shouldUseLocalFoundation = false } } So here we decide if we are going to use iPhone ML or my backend-remote?
2
0
329
2d
SubscriptionStoreView crashes on macOS Catalyst
I have an iOS and iPadOS app that also runs on macOS Catalyst. The user is able to view their subscription using the SubscriptionStoreView with two SubscriptionOptionGroups. The documentation does not mention these are supported on macOS Catalyst and the app crashes when attempting to show the SubscriptionStoreView on macOS Catalyst. If not supported, how can the user manage their subscription on macOS?
1
0
135
3d
NavigationTitle in LiquidGlass style
Hello everyone. I want to do navigationTitle (located on the top side on MacOS system) in LiquidGlass style. now my solution look like: just black rectangle. But i want like this: opacity and LiquidGlass. Like in Photo app in MacOS. Please help me, thank you in advance. My code: struct RootView: View { @Environment(\.horizontalSizeClass) var hSize var body: some View { if hSize == .regular { DesktopLayout() .navigationTitle("title") .toolbarBackground(.ultraThinMaterial, for: .automatic) } else { MobileLayout() } } }
1
0
503
4d
SwiftUI toolbar with IDs crash since macOS 15
I understand this is a known issue, but it’s truly unacceptable that it remains unresolved. Allowing users to customize toolbars is a fundamental macOS feature, and it has been broken since the release of macOS 15. How is it possible that this issue persists even in macOS 15.3 beta (24D5040f)? FB15513599 import SwiftUI struct ContentView: View { @State private var showEditItem = false var body: some View { VStack { VStack { Text("Instructions to reproduce the crash") .font(.title) .padding() Text(""" 1. Click on "Toggle Item" 2. In the menu go to File > New Window 3. In new window, click on "Toggle Item" """) } .padding() Button { showEditItem.toggle() } label: { Text("Toggle Item") } } .padding() .toolbar(id: "main") { ToolbarItem(id: "new") { Button { } label: { Text("New…") } } if showEditItem { ToolbarItem(id: "edit") { Button { } label: { Text("Edit…") } } } } } }
7
3
696
5d
How to stop ios 26 glass effect UI in ios app
Hi everyone, I want to avoid the iOS 26 Liquid Glass effect in my app’s UI. While researching, I found the following possible solution: Steps: Go to Info.plist Add the key: UIDesignRequiresCompatibility Type: Boolean Value: YES I have a few questions about this approach: According to the Apple Developer website, this seems to be a temporary solution. How long will this continue to work, and what would be the recommended long-term solution? Which iOS versions does this support (both older and upcoming versions)? If this method is not recommended, is there another way to disable or avoid the glass effect across the entire app without making major UI changes? Any guidance or suggestions would be greatly appreciated. Thank you!
1
0
162
6d
Liquid Glass Button animating when behind a view when `.interactive()` modifier is applied
When using the .glassEffect modifier on a button in swiftui combined with the .interactive() modifier, the button continues to show the interactive animation even when it’s covered by another element. Example: ZStack { Button { print("Button overlayed by ZStack") // Does not trigger, but interactive animation still plays } label: { image } .glassEffect(.regular.interactive()) Rectangle().fill(.black.opacity(0.7)) } This occurs with overlays, ZStacks, and even if the overlay is a button. Example below: EDIT: It seems like rocketsim's gif recording doesnt show the bug for some reason... really strange... Edit 2: reuploaded gif, recorded as mp4 and converted to gif seems to have worked... Feedback ID: FB22054300 I've attached this sample app to my feedback ticket to help with debugging the issue. It doesn't look like I can share it in this post though.
2
1
151
6d
DynamicViewContent and drop validation (macOS)
If I see it correctly, it is currently not possible to validate a drop operation on a DynamicViewContent when using dropDestination? Just a simple example: Let's say I build a folder view on macOS where I can arrange folders freely. In this case I need to use DynamicViewContent.dropDestination to get an insertion index on drop. However, it seems that methods like dropConfiguration do not have any effect. Als dropDestionation(…, isTargeted:) seems not to be available. Here is my sample code: struct FolderRow: View { let folder: Folder var body: some View { DisclosureGroup(isExpanded: .constant(true)) { ForEach(folder.children) { child in FolderRow(folder: child) } .dropDestination(for: Folder.self) { item, idx in print("Dropped at \(idx)") } } label: { Label(folder.name, systemImage: "folder") .draggable(folder) .dropDestination(for: Folder.self) { items, _ in print("Dropped on Item") } } .dropConfiguration { session in DropConfiguration(operation: .move) } } } struct ContentView: View { @State private var folder: Folder = Folder.sampleData @State private var selection: Set<UUID> = [] var body: some View { NavigationSplitView { List(selection: $selection) { FolderRow(folder: folder) } } detail: { EmptyView() } } } The dropConfiguration is applied on the Label (in this case the "Move" cursor is used instead of the "Copy" cursor). Is there any way to do that or is it just an omission in Swift UI?
0
0
79
6d
Access Relationship value from deleted model tombstone in SwiftData.
I’m developing an app using SwiftData. In my app, I have two models: User and Address. A user can have multiple addresses. I’m trying to use SwiftData History tracking to implement some logic when addresses are deleted. Specifically, I need to determine which user the address belonged to. From the documentation, I understand that you can preserve attributes from deleted models in a tombstone object using @Attribute(.preserveValueOnDeletion). However, this isn’t working when I try to apply this to a relationship value. Below is a simplified example of my attempts so far. I suspect that simply adding @Attribute(.preserveValueOnDeletion) to a relationship isn’t feasible. If that’s indeed the case, what would be the recommended approach to identify the user associated with an address after it has been deleted? Thank you. @Model class User { var name: String @Relationship(deleteRule: .cascade, inverse: \Address.user) var addresses: [Address] = [] init(name: String) { self.name = name } } @Model class Address { var adress1: String var address2: String var city: String var zip: String @Attribute(.preserveValueOnDeletion) var user: User? init(adress1: String, address2: String, city: String, zip: String) { self.adress1 = adress1 self.address2 = address2 self.city = city self.zip = zip self.user = user } } for transaction in transactions { for change in transaction.changes { switch change { case .delete(let deleted): if let deleted = deleted as? any HistoryDelete<Address> { if let user = deleted.tombstone[\.user] { //this is never executed } } default: break } } }
1
0
84
1w
What is the lifecycle of onReceive subscriptions in SwiftUI views?
I'm trying to better understand how the onReceive modifier behaves in SwiftUI, specifically how its subscription lifecycle relates to view updates. Consider this example: TextField("Name", text: $name) .onReceive(Just(name)) { value in print(value) } This closure runs every time name changes. A common explanation is that SwiftUI recomputes body, which creates a new Just(name) publisher each time. However, this raises some questions for me about how onReceive actually works internally: When SwiftUI recomputes body, is the onReceive modifier recreated and resubscribed? Does SwiftUI automatically cancel the previous subscription when the view updates?
0
0
48
1w
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
3
0
527
1w
Crash when Displaying RealityView on Multiple Screen only Connecting with Xcode
I have an iOS app that uses RealityView to display some models and interact with them, and the app uses regular iOS app navigations, then a challenge I'm facing is how to maintain multiple RealityView on multiplescreens. For example Screen A has a RealityView, and then I navigate to Screen B (also has a RealityView) using stack based navigation, when I do so I got a crash -[MTLDebugRenderCommandEncoder validateCommonDrawErrors:]:5970: failed assertion `Draw Errors Validation Fragment Function(fsRealityPbr): argument envProbeTable[0] from Buffer(7) with offset(0) and length(16) has space for 16 bytes, but argument has a length(864). Fragment Function(fsRealityPbr): incorrect type of texture (MTLTextureType2D) bound at Texture binding at index 20 (expect MTLTextureTypeCubeArray) for envProbeDiffuseArray[0]. Interestingly this crash only happens when debugging with Xcode, not happens when the app runs on its own. I'm not sure what I'm doing is anti-pattern or it's some Xcode debugging limitation.
0
0
727
1w
Backgrounded app - Local Notifications
I'm working on an app that syncs with Apple Health events. Every time an event occurs, the app should send a notification. The problem occurs when the app is backgrounded or force-closed; it can no longer send local notifications, and because these events can occur at any time, scheduled notifications can't be used. I'm just wondering if anyone's found a creative way around this. I know we can't override system behaviour, I'm just thinking of other alternative solutions for the matter.
1
0
114
1w