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

iOS 26: Enabling "Reduce Transparency" causes a persistent white bar where the tab bar was hidden, blocking user interaction
Hi everyone, We're experiencing a bug on iOS 26 that only occurs when the user has Reduce Transparency enabled in Accessibility settings. App structure: Our app uses a TabView with a standard tab bar. Inside each tab, we use a NavigationStack. The tab bar is visible on root-level screens, and hidden on all pushed destinations using: .toolbar(.hidden, for: .tabBar) The problem: On iOS 26 with Reduce Transparency off (Liquid Glass active) — everything works correctly. The tab bar hides as expected. On iOS 26 with Reduce Transparency on — a white bar appears at the bottom of the screen in every place where the tab bar is hidden. This white bar: Overlaps content at the bottom of the screen. Blocks scroll, tap, and all user interactions in that area. We also tried: .toolbarBackground(.hidden, for: .tabBar) Removing all custom UITabBarAppearance configuration The only workaround we found is setting UIDesignRequiresCompatibility = YES in Info.plist, which reverts the entire app to the pre-iOS 26 design — not a viable long-term solution. What can we do? Thanks in advance.
2
0
135
18h
NSFileSandboxingRequestRelatedItemExtension: Failed to issue extension
Hi there, I have an SwiftUI app that opens a user selected audio file (wave). For each audio file an additional file exists containing events that were extracted from the audio file. This additional file has the same filename and uses the extension bcCalls. I load the audio file using FileImporter view modifier and within access the audio file with a security scoped bookmark. That works well. After loading the audio I create a CallsSidecar NSFilePresenter with the url of the audio file. I make the presenter known to the NSFileCoordinator and upon this add it to the FileCoordinator. This fails with NSFileSandboxingRequestRelatedItemExtension: Failed to issue extension for; Error Domain=NSPOSIXErrorDomain Code=3 "No such process" My Info.plist contains an entry for the document with NSIsRelatedItemType set to YES I am using this kind of FilePresenter code in various live apps developed some years ago. Now when starting from scratch on a fresh macOS26 system with most current Xcode I do not manage to get it running. Any ideas welcome! Here is the code: struct ContentView: View { @State private var sonaImg: CGImage? @State private var calls: Array<CallMeasurements> = Array() @State private var soundContainer: BatSoundContainer? @State private var importPresented: Bool = false var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") if self.sonaImg != nil { Image(self.sonaImg!, scale: 1.0, orientation: .left, label: Text("Sonagram")) } if !(self.calls.isEmpty) { List(calls) {aCall in Text("\(aCall.callNumber)") } } Button("Load sound file") { importPresented.toggle() } } .fileImporter(isPresented: $importPresented, allowedContentTypes: [.audio, UTType(filenameExtension: "raw")!], onCompletion: { result in switch result { case .success(let url): let gotAccess = url.startAccessingSecurityScopedResource() if !gotAccess { return } if let soundContainer = try? BatSoundContainer(with: url) { self.soundContainer = soundContainer self.sonaImg = soundContainer.overviewSonagram(expectedWidth: 800) let callsSidecar = CallsSidecar(withSoundURL: url) let data = callsSidecar.readData() print(data) } url.stopAccessingSecurityScopedResource() case .failure(let error): // handle error print(error) } }) .padding() } } The file presenter according to the WWDC 19 example: class CallsSidecar: NSObject, NSFilePresenter { lazy var presentedItemOperationQueue = OperationQueue.main var primaryPresentedItemURL: URL? var presentedItemURL: URL? init(withSoundURL audioURL: URL) { primaryPresentedItemURL = audioURL presentedItemURL = audioURL.deletingPathExtension().appendingPathExtension("bcCalls") } func readData() -> Data? { var data: Data? var error: NSError? NSFileCoordinator.addFilePresenter(self) let coordinator = NSFileCoordinator.init(filePresenter: self) NSFileCoordinator.addFilePresenter(self) coordinator.coordinate(readingItemAt: presentedItemURL!, options: [], error: &error) { url in data = try! Data.init(contentsOf: url) } return data } } And from Info.plist <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeExtensions</key> <array> <string>bcCalls</string> </array> <key>CFBundleTypeName</key> <string>bcCalls document</string> <key>CFBundleTypeRole</key> <string>None</string> <key>LSHandlerRank</key> <string>Alternate</string> <key>LSItemContentTypes</key> <array> <string>com.apple.property-list</string> </array> <key>LSTypeIsPackage</key> <false/> <key>NSIsRelatedItemType</key> <true/> </dict> <dict> <key>CFBundleTypeExtensions</key> <array> <string>wav</string> <string>wave</string> </array> <key>CFBundleTypeName</key> <string>Windows wave</string> <key>CFBundleTypeRole</key> <string>Editor</string> <key>LSHandlerRank</key> <string>Alternate</string> <key>LSItemContentTypes</key> <array> <string>com.microsoft.waveform-audio</string> </array> <key>LSTypeIsPackage</key> <integer>0</integer> <key>NSDocumentClass</key> <string></string> </dict> </array> Note that BatSoundContainer is a custom class for loading audio of various undocumented formats as well as wave, Flac etc. and this is working well displaying a sonogram of the audio. Thx, Volker
12
0
491
1d
manageSubscriptionsSheet resulting in "No connection"
I have an iOS app (SwiftUI) that includes recurring subscriptions. To allow users to manage their subscriptions I have implemented manageSubscriptionsSheet according to apple documentation. When I published the app last year for iOS17 and iOS18 this was working well. Now I have gotten a user report that this features yields No connection error instead of the abonnements on iOS26. I have tested on my iPad running iOS 26 as well as on the simulator with iOS 26 and 18. In all cases I get the error. I can press Retry in the dialog and am prompted for AppStore credentials After entering them, again the same error. I can not find a single hint on why and how to fix it. Best wishes, Volker
2
0
43
1d
Reality View Preserves Camera Transform when toggling Virtual & Spatial Tracking modes
When switching from RealityView’s .spatialTracking camera mode to .virtual camera mode, the camera’s orientation relative to the scene is preserved permanently with no way to reset to default World-Up orientation. Since .spatialTracking’s camera mode will always have a non-default orientation, switching to .virtual camera mode ensures that the cameras’s ‘UP’ direction will never match the device display’s ‘UP’ direction as is default. This is especially noticeable when using .orbit camera controls, as the orbit’s UP direction matches the scene, not camera, and all rotation directions give unexpected results. Expected: When setting virtual camera mode after using spatialTracking camera mode, either 1. The Virtual Camera orientation returns to default (world up). Or 2. A 'content.camera.resetOrientation()' call is made available which resets the RealityView camera to default orientation. Reality: Switching from .spatialTracking -> .virtual camera mode permanently locks the .virtual camera’s orientation the final frame of the .spatialTracking camera’s rotation (relative to the RealityView content scene). One imperfect workaround is to reset / rebuild the entire RealityView after changing modes (by resetting .id() or otherwise. This is not ideal as it causes everything inside the make closure to rerun, which not only is a performance & time cost, visually incurs a flicker and can also be problematic with managing increasingly complicated views. Another imperfect alternative is to use more than one RealityView - which is not ideal as it incurs double the base ram usage, significantly increases code, and seemingly goes against the intent of being able to change the camera .virtual/.spatatialTracking mode at will. Code Sample: import SwiftUI import RealityKit struct RKSpatialVirtualToggle: View { @State var showAR: Bool = false var body: some View { RealityView { content in let cube = ModelEntity(mesh: .generateBox(size: 0.25), materials: [SimpleMaterial()]) cube.position.z = -1 content.add(cube) content.camera = showAR ? .spatialTracking : .virtual content.cameraTarget = cube } update: { content in content.camera = showAR ? .spatialTracking : .virtual } .realityViewCameraControls(.orbit) VStack{ Spacer() Button("Toggle AR"){ showAR.toggle() } .buttonStyle(.borderedProminent) } } } Xcode Version: Version 26.0 (17A324) iOS Version: iOS 26.5 (23F75) Tested on devices, iPhone 12 Pro, iPhone 15 Pro
1
0
37
1d
SecureField dots invisible in dark mode when iOS suggests and fills a strong password
I am using SwiftUI's native SecureField. When a user types their password manually, the dots render correctly in both light and dark mode. However, when iOS suggests and autofills a strong generated password, the dots become invisible in dark mode. Switching to light mode shows that they are there. Is there a supported way to force SecureField to re-render its secure entry dots correctly after iOS fills in a strong generated password in dark mode? import SwiftUI let warmMustard = Color(red: 0.780, green: 0.659, blue: 0.290) let lightText = Color(red: 0.973, green: 0.961, blue: 0.933) let darkText = Color(red: 0.118, green: 0.118, blue: 0.118) struct SecureFieldTestView: View { @Environment(\.colorScheme) var colorScheme @State private var username = "" @State private var password = "" @State private var confirmPassword = "" var body: some View { ZStack { Color(colorScheme == .dark ? UIColor.black : UIColor.white) .ignoresSafeArea() VStack(spacing: 20) { Text("Dark mode dot reproduction") .foregroundColor(colorScheme == .dark ? .white : .black) TextField("Username", text: $username) .textContentType(.username) .autocorrectionDisabled() .textInputAutocapitalization(.never) .padding() .background(colorScheme == .dark ? Color.black : Color.white) .cornerRadius(8) .foregroundColor(colorScheme == .dark ? .white : .black) .overlay(RoundedRectangle(cornerRadius: 8).stroke(warmMustard, lineWidth: 2)) SecureField("Password", text: $password) .textContentType(.newPassword) .padding() .background(colorScheme == .dark ? Color.black : Color.white) .cornerRadius(8) .foregroundColor(colorScheme == .dark ? .white : .black) .overlay(RoundedRectangle(cornerRadius: 8).stroke(warmMustard, lineWidth: 2)) SecureField("Confirm Password", text: $confirmPassword) .textContentType(.newPassword) .padding() .background(colorScheme == .dark ? Color.black : Color.white) .cornerRadius(8) .foregroundColor(colorScheme == .dark ? .white : .black) .overlay(RoundedRectangle(cornerRadius: 8).stroke(warmMustard, lineWidth: 2)) } .padding(.horizontal, 32) } } } #Preview { SecureFieldTestView() }
2
0
69
1d
How to set the Locale.current to be same as the Environment locale?
I have this code As you can see, the locale of the Environment is different from the Locale given by .current. This is a problem for me because I have code that uses String(localized:) and AttributedString. I would like to be able to preview them with the locale I set in the Environment without any additional work on my part. I assumed these Apis would use the locale set by the environment but no, it uses the locale as decided by the schema used to build the preview app. The current solution I have is to manually change the App Language in the Preview's scheme to be whatever I need to correctly localize the language in Preview.
1
0
57
1d
How to set custom height for keyboard extension without resize flicker?
Description I'm developing a custom keyboard extension using UIInputViewController and need to set a specific height of 268 points. The keyboard functions correctly, but there's a visible flicker and resize animation during launch that I cannot eliminate. The Problem When the keyboard launches, iOS provides incorrect heights before settling on the correct one. At launch, the view starts at 0×0. Around 295ms later, iOS sets the frame to 440×956 which is full screen height and wrong. Around 373ms, iOS changes it to 440×452 which is still wrong. Finally around 390ms, iOS settles at 440×268 which matches our constraint. This causes visible flicker as the view resizes three times rapidly. The keyboard appears to shrink from full screen down to the correct height, and users can clearly see this animation happening. What I've Tried I've tried adding a height constraint on self.view which gives me the correct height but causes the visible flicker. I created a custom UIInputView subclass and overrode intrinsicContentSize to return my desired height. iOS completely ignores this and gives random heights like 471pt, 680pt, or 956pt instead. I set allowsSelfSizing to true on my UIInputView subclass. iOS ignores this property. I set preferredContentSize on the view controller. iOS ignores this as well. I tried adding the constraint in viewDidAppear instead of viewDidLoad, thinking iOS might have settled by then. It still causes flicker. I overrode the frame and bounds setters on my UIInputView to clamp the height to my desired value. iOS bypasses these overrides somehow. I overrode layoutSubviews to force the correct height after the super call. iOS still applies its own height. Specific Question What is the correct API or technique to specify a keyboard extension's height that iOS will respect immediately upon launch, without triggering the resize animation sequence? Other third-party keyboards like Grammarly and SwiftKey appear to have solved this problem. Their keyboards appear at the correct height without any visible flicker. How do they achieve this? Expected Outcome The keyboard should appear at 268pt height on the first frame with no visible resize animation. Steps to Reproduce Create a new iOS App project in Xcode and add a Keyboard Extension target. In KeyboardViewController.swift, add a height constraint in viewDidLoad: override func viewDidLoad() { super.viewDidLoad() let heightConstraint = view.heightAnchor.constraint(equalToConstant: 268) heightConstraint.priority = .defaultHigh heightConstraint.isActive = true let label = UILabel() label.text = "Demo Keyboard" label.textAlignment = .center label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: view.centerXAnchor), label.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } Build and run on a physical device. Enable the keyboard in Settings, then General, then Keyboard, then Keyboards. Open any app with a text field and switch to the custom keyboard using the globe button. Observe the height changing from around 956pt to 452pt to 268pt with visible animation. Environment iOS 17 and iOS 18 and 26.2, Xcode 16 and Xcode 26, affects all iPhone models tested, reproducible on both simulator and physical device.
1
3
206
1d
SwiftData 'simple' migration failing
This is a long post, so let me start with a summary: I am attempting to implement what "ought to be" a simple SwiftData migration, and am receiving the following fatal error from the ModelContainer initializer: NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." The crash occurs both in the Simulator and on a physical device. Both the original schema and the new schema load and run as expected if loaded from scratch — so I conclude the Models are OK; it is the migration from the original schema to the new schema which is the issue. I have reported this as FB22652791 and Technical Incident Case # 19893980. I have two model projects available — one contrived, the other using my actual SwiftData models. Now the Details I am developing a SwiftUI/SwiftData app. I am (currently) using Xcode 26.5-beta-3. I set up an alpha-test build using the following approach: public class DatabaseSchema { public let dbSchema: Schema = Schema([ Model1.self, ... , Model16.self ], version: Schema.Version(0, 9, 0)) public var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false) do { container = try ModelContainer(for: dbSchema, migrationPlan: nil, configurations: [modelConfiguration]) } catch { fatalError("Failed to creae model conainer") } return container } This defines database version 0.9. For version 1.0, I made three changes to the database: added an attribute of type String to Model2. added three attributes of type [Struct], where Struct conforms to Codable, Equatable and Hashable to Model3, and added a new model (which I'll call Model17) I define two schemas: public enum Schema090: VersionedSchema { public static var versionIdentifier = Schema.Version(0, 9, 0) public static var models: [any PersistentModel.Type] = [ Model1.self, Schema090.Model2.self, Schema090.Model3.self, ... ] } and public enum Schema100: VersionedSchema { public static var versionIdentifier = Schema.Version(1, 0, 0) public static var models: [any PersistentModel.Type] = [ Model1.swift, Schema100.Model2.self, Schema100.Model3.self, ..., Model16.self, Schema100.Model17.self ] } For models that changed, I use the following approach: public typealias Model3 = Schema100.Model3 extension Schema090 { @Model final class Model3 { ... } public init() { ... } } extension Schema100 { @Model final class Model3 { ... <added attributes, initialized> } public init() { ... } } The DatabaseSchema class was modified as follows: public class DatabaseSchema { public let dbSchema: Schema = Schema([ Model1.self, Schema100.Model2.self, Schema100.Model3.self, ... , Model16.self, Schema100.Model17.self ], version: Schema.Version(1, 0, 0)) public var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false) do { container = try ModelContainer(for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) } catch { fatalError("Failed to creae model conainer") } return container } where the migration plan is the trivial custom migration that makes sure that all added attributes of existing records are properly initialized. enum MigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] = [ Schema090.self, Schema100.self ] static var stages: [MigrationStage] = [version090ToVersion100] static let version090ToVersion100 = MigrationStage(fromVersion: Schema090.self, toVersion: Schema100.self, willMigrate: { _ in }, didMigrate: { context in let models = try context.fetch( FetchDescriptor<Schema100.Model3>()) for model in models { < initial the added attributes > { try context.save() }) } This is all simple stuff. Nothing particularly fancy here. But running this code always crashes in the ModelContainer initializer. In my two sample projects, I get two different error messages — in the contrived example, the error message is Code=134110 "An error occurred during persistent store migration." reason=Cannot migrate store in-place: Validation error missing attribute values on mandatory destination attribute, ... and in the sample project that uses my actual data model, I get NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." My Thoughts Since obviously most folks are doing SwiftData migrations without the problems I am experiencing, the obvious possibilities are I'm doing something stupid that I just don't see. There is a problem because the original schema was given a version value of Schema.Version(0, 9, 0). (i.e., major version number was 0) There is a problem because I am adding an attribute of type [Struct] where Struct is Codable, Hashable, and Equatable. I.e., migration isn't working properly with attributes which are stored as their codable representations. Or maybe something else? In any case, any help you can offer would be greatly appreciated.
7
0
592
1d
AttributedString Localization does not seem to work
I have this code struct TestAppleSuggestion: View { @Environment(\.locale) var locale: Locale var body: some View { VStack { VStack { Text("locale: \(locale.identifier)") Text(AttributedString(localized: LocalizedStringResource( "welcome", locale: locale ))) Text(AttributedString(localized: "welcome", locale: locale )) } } } } #Preview { TestAppleSuggestion().environment(\.locale, Locale(identifier: "fr-CA")) } Heres What I see in SwiftUi Previews The Localization is working for the LocalizedStringResource but not to the AttributedString. Why?
3
0
166
1d
NavigationSplitView no longer pops back to the root view when selection = nil in iOS 26.4 (with a nested TabView)
In iOS 26.4 (iPhone, not iPad), when a NavigationSplitView is combined with a nested TabView, it no longer pops back to the root sidebar view when the List selection is set to nil. This has been working fine for at least a few years, but has just stopped working in iOS 26.4. Here's a minimal working example: import SwiftUI struct ContentView: View { @State var articles: [Article] = [Article(articleTitle: "Dog"), Article(articleTitle: "Cat"), Article(articleTitle: "Mouse")] @State private var selectedArticle: Article? = nil var body: some View { NavigationSplitView { TabView { Tab { List(articles, selection: $selectedArticle) { article in Button { selectedArticle = article } label: { Text(article.title) } } } label: { Label("Explore", systemImage: "binoculars") } } } detail: { Group { if let selectedArticle { Text(selectedArticle.title) } else { Text("No selected article") } } .navigationBarBackButtonHidden(true) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Close", systemImage: "xmark") { selectedArticle = nil } } } } } } struct Article: Identifiable, Hashable { let id: String let title: String init(articleTitle: String) { self.id = articleTitle self.title = articleTitle } } First, I'm aware that nesting a TabView inside a NavigationSplitView is frowned upon: Apple seems to prefer NavigationSplitView nested inside a Tab. However, for my app, that leads to a very confusing user experience. Users quickly get lost because they end up with different articles open in different tabs and it doesn't align well with my core distinction between two "modes": article selection mode and article reading mode. When the user is in article selection mode (sidebar view), they can pick between different ways of selecting an article (Explore, Bookmarks, History, Search), which are implemented as "tabs". When they pick an article from any tab they jump into article reading mode (the detail view). Second, I'm using .navigationBarBackButtonHidden(true) to remove the auto back button that pops back to the sidebar view. This button does still work in iOS 26.4, even with the nested TabView. However, I can't use the auto back button because my detail view is actually a WebView with its own back/forward logic and UI. Therefore, I need a separate close button to exit from the detail view. My close button sets selectedArticle to nil, which (pre-iOS 26.4) would trigger the NavigationSplitView to pop back to the sidebar view. For some reason, in iOS 26.4 the NavigationSplitView doesn't seem to bind correctly to the List's selection parameter, specifically when there's a TabView nested between them. Or, rather, it binds, but fails to pop back when selection becomes nil. One option is to replace NavigationSplitView with NavigationStack (on iPhone). NavigationStack still works with a nested TabView, but it creates other downstream issues for me (as well as forcing me to branch for iPhone and iPad), so I'd prefer to continue using NavigationSplitView. Does anyone have any ideas about how to work around this problem? Is there some way of explicitly telling NavigationSplitView to pop back to the sidebar view on iPhone? (I've tried setting the column visibility but nothing seems to work). Thanks for any help!
1
1
166
3d
Is it possible to focus a non-textField on iPadOS in SwiftUI?
I would like to implement a focus-based Menu-Bar command in my SwiftUI iPadOS app, or react to key command while certain elements are focused. Traditionally, this requires using @FocusedValue and focusable() and focused, however, it appears that setting a @FocusState on macOS will work, but setting a @FocusState on iPadOS will never work. How can this API work and support MenuBar commands and keyboard inputs? It kind of has an accessibility impact as well. Not all users are going to know, or want to turn on "full keyboard control" for basic interactions. Here's a small sample that doesn't appear to focus on iPadOS: struct FocusableTestView: View { @FocusState private var isRectFocused: Bool var body: some View { VStack { // This text field should focus the custom input when pressing return: TextField("Enter text", text: .constant("")) .textFieldStyle(.roundedBorder) .onSubmit { isRectFocused = true } .onKeyPress(.return) { isRectFocused = true return .handled } // This custom "input" should focus itself when tapped: Rectangle() .fill(isRectFocused ? Color.accentColor : Color.gray.opacity(0.3)) .frame(width: 100, height: 100) .overlay( Text(isRectFocused ? "Focused" : "Tap me") ) .focusable(true) .focused($isRectFocused) .onTapGesture { isRectFocused = true print("Focused rectangle") } // The focus should be able to be controlled externally: Button("Toggle Focus") { isRectFocused.toggle() } .buttonStyle(.bordered) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) } }
0
0
149
6d
Focusable doesn't work on iPad with external keyboard
I have a custom input view in my app which is .focusable(). It behaves similar to a TextField, where it must be focused in order to be used. This works fine on all platforms including iPad, except when when an external keyboard is connected (magic keyboard), in which case it can't be focused anymore and becomes unusable. Is there a solution to this, or a workaround? My view is very complex, so simple solutions like replacing it with a native view isn't possible, and I must be able to pragmatically force it to focus. Here's a very basic example replicating my issue. Non of the functionality works when a keyboard is connected: struct FocusableTestView: View { @FocusState private var isRectFocused: Bool var body: some View { VStack { // This text field should focus the custom input when pressing return: TextField("Enter text", text: .constant("")) .textFieldStyle(.roundedBorder) .onSubmit { isRectFocused = true } .onKeyPress(.return) { isRectFocused = true return .handled } // This custom "input" should focus itself when tapped: Rectangle() .fill(isRectFocused ? Color.accentColor : Color.gray.opacity(0.3)) .frame(width: 100, height: 100) .overlay( Text(isRectFocused ? "Focused" : "Tap me") ) .focusable(true, interactions: .edit) .focused($isRectFocused) .onTapGesture { isRectFocused = true print("Focused rectangle") } // The focus should be able to be controlled externally: Button("Toggle Focus") { isRectFocused.toggle() } .buttonStyle(.bordered) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) } }
2
0
291
6d
Is updateUIViewController always called immediately after makeUIViewController?
I'm in the unenviable position of needing the current UIViewController to keep an external library happy. Essentially, I need to do this in SwiftUI: import LibraryOutOfMyControl ViewControllerReader { viewController in Button("Action") { LibraryOutOfMyControl.action(with: viewController) } } My simple attempt below functions correctly but I'm relying on makeUIViewController always being immediately followed by updateUIViewController. Is the a reasonable assumption or should I set everything up assuming updateUIViewController might never be called? struct ViewControllerReader<Content>: UIViewControllerRepresentable where Content: View { @ViewBuilder var content: (UIViewController) -> Content func makeUIViewController(context: Context) -> UIHostingController<Content> { UIHostingController(rootView: content(UIViewController())) } func updateUIViewController(_ uiViewController: UIHostingController<Content>, context: Context) { uiViewController.rootView = content(uiViewController) uiViewController.view.isUserInteractionEnabled = context.environment.isEnabled } func sizeThatFits(_ proposal: ProposedViewSize, uiViewController: UIHostingController<Content>, context: Context) -> CGSize? { uiViewController.sizeThatFits(in: proposal.replacingUnspecifiedDimensions()) } }
0
0
106
1w
SwiftUI navigation bar button color changes depending on whether the root view is a ScrollView or VStack
I have a SwiftUI view inside a NavigationStack with a custom navigation bar background color. I want the navigation bar buttons to have a consistent color throughout the app. The issue is that the navigation bar button color changes depending on the first/root view in the body. When the root view is a ScrollView var body: some View { ScrollView { // content } .toolbarBackground(Color(red: 0.02, green: 0.27, blue: 0.13), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } The navigation bar buttons appear white. However, if I replace the ScrollView with a VStack, while keeping the same modifiers, the navigation bar buttons appear black: var body: some View { VStack { // content } .toolbarBackground(Color(red: 0.02, green: 0.27, blue: 0.13), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } The navigation bar buttons appear black. How can I make the navigation bar buttons stay the same colour in both cases?
1
0
184
1w
.disabled() doesn't VISUALLY disable buttons inside ToolbarItem on iOS 26 devices
[Also submitted as FB19313064] The .disabled() modifier doesn't visually disable buttons inside a ToolbarItem container on iOS 26.0 (23A5297i) devices. The button looks enabled, but tapping it doesn't trigger the action. When deployment target is lowered to iOS 18 and deployed to an iOS 18 device, it works correctly. It still fails on an iOS 26 device, even with an iOS 18-targeted build. This occurs in both the Simulator and on a physical device. Screen Recording Code struct ContentView: View { @State private var isButtonDisabled = false private var osTitle: String { let version = ProcessInfo.processInfo.operatingSystemVersion return "iOS \(version.majorVersion)" } var body: some View { NavigationStack { VStack { Button("Body Button") { print("Body button tapped") } .buttonStyle(.borderedProminent) .disabled(isButtonDisabled) Toggle("Disable buttons", isOn: $isButtonDisabled) Spacer() } .padding() .navigationTitle("Device: \(osTitle)") .navigationBarTitleDisplayMode(.large) .toolbar { ToolbarItem { Button("Toolbar") { print("Toolbar button tapped") } .buttonStyle(.borderedProminent) .disabled(isButtonDisabled) } } } } }
8
3
734
1w
SwiftUI Button with Image view label has smaller hit target
[Also submitted as FB20213961] SwiftUI Button with a label: closure containing only an Image view has a smaller tap target than buttons created with a Label or the convenience initializer. The hit area shrinks to the image bounds instead of preserving the standard minimum tappable size. SCREEN RECORDING On a physical device, the difference is obvious—it’s easy to miss the button. Sometimes it even shows the button-tapped bounce animation but doesn’t trigger the action. SYSTEM INFO Xcode Version 26.0 (17A321) macOS 15.6.1 (24G90) iOS 26.0 (23A340) SAMPLE CODE The following snippet shows the difference in hit targets between the convenience initializer, a Label, and an Image (the latter two in a label: closure). // ✅ Hit target is entire button Button("Button 1", systemImage: "1.square.fill") { print("Button 1 tapped") } // ✅ Hit target is entire button Button { print("Button 2 tapped") } label: { Label("Button 2", systemImage: "2.square.fill") } // ❌ Hit target is smaller than button Button { print("Button 3 tapped") } label: { Image(systemName: "3.square.fill") }
6
4
482
1w
Changing systemImage value for Image, logs "fopen failed for data file".
I'm getting a log error and a slight delay in the UI when displaying a system image that changes at the end of a sequence. I'm using a ternary operator to determine the image; the fact that the image changes seem to be the issue, rather than the value itself. The issue only occurs for a newly installed app, and not when the app is rerun. (I'm using similar code to display an onboarding sequence after installation.) This happens on device (iphone 15 pro v25.6) and simulator (iphone 17 pro v25.6 and iphone 16 pro v18.5); xcode 26.5 (17F42). Console errors (device and iphone 17 simulator): fopen failed for data file: errno = 2 (No such file or directory) fopen failed for data file: errno = 2 (No such file or directory) Repro Code: import SwiftUI struct ContentView: View { // NOTE: error only occurs with new install. @State private var currentItem = 0 @State private var totalItems: Int = 4 var body: some View { VStack(spacing: 0) { Spacer() Text("totalItems: \(totalItems)") TabView(selection: $currentItem) { ForEach(0...totalItems, id: \.self) { item in Text("\(item) ~ \(currentItem)") .tag(item) } } //TV .tabViewStyle(.page(indexDisplayMode: .never)) .frame(height: 200) Button { if currentItem < totalItems { currentItem += 1 currentItem = min(totalItems, currentItem) } } label: { let imgString: String = (currentItem == totalItems ? "arrowshape.turn.up.right" : "arrowshape.right") // error // let imgString: String = ((currentItem == totalItems) ? "x.circle" : "smallcircle.filled.circle") // error // let imgString: String = "smallcircle.filled.circle" // no error // let imgString: String = "x.circle" // no error Text("\(imgString)") // if only print text, no error, so issue seems to be with Image. Image(systemName: imgString) } Spacer() } } } Click through the button sequence to see issue at end of sequence. Uncomment the various imgString lines to see indicated differences in behavior. Need to delete app each time to repro issue. Running in simulator on iphone 16 Pro iOS 18.5 has slightly different error messages: fopen failed for data file: errno = 2 (No such file or directory) Errors found! Invalidating cache... fopen failed for data file: errno = 2 (No such file or directory) Errors found! Invalidating cache...
1
0
65
1w
iOS 26 rendering gap on scroll surfaces — lower scroll view does not render
On iOS 26 (26.0–26.5), a rectangular region in the lower half of the screen sometimes does not render while the content underneath remains laid out and interactive — scrolling works, hit testing succeeds, and rows visibly emerge from behind the floating tab bar as you scroll. This is a render-server / compositor gap, not a layout or safe-area issue. We see it on both UIKit and SwiftUI scroll surfaces inside the same UITabBarController: UIKit: UICollectionView with UICollectionViewFlowLayout (sectionInsetReference = .fromSafeArea) SwiftUI: List(.plain) nested in TabView(.page) inside a UIHostingController Confirmed on iPhone 16 Pro, iPhone 17 Pro, iPhone 13 Pro Max. Community threads (linked below) report the same symptom in Messages, Notes, Safari, Mail, and the App Store. Questions for Apple Is this acknowledged as an OS-level regression, and is a fix targeted for an upcoming iOS 26.x release? Is there a deterministic repro? We've tried background/foreground cycles, push notifications mid-scroll, tab switches during inertia, lock/unlock, orientation flips, simulated memory warnings, layout-invalidation storms, and trait-collection cycles — none reliably trigger it on our test devices. Is there a developer-side mitigation (e.g. avoiding specific UIVisualEffectView / Glass configurations, opting out of a rendering optimization) until a system fix lands? Is there a runtime signal on CALayer or UIScrollView we can inspect to detect this gap state and force a recovery (tile redraw, backing-store discard, etc.)? Notes We cannot reproduce locally. Affected users hit it organically; once it appears it persists across re-layout until the view controller is torn down. Community reports consistently mention Reduce Transparency being enabled on affected devices, and toggling it off clears the issue for many. In our own testing, RT alone is not sufficient to trigger the bug — it appears to be a contributing condition rather than the trigger. References: Apple Discussions: https://discussions.apple.com/thread/256182149 Reddit r/ios (multiple system apps): https://www.reddit.com/r/ios/comments/1nlzn7f/some_apps_cutting_off_half_the_display/ https://www.idownloadblog.com/2026/03/23/webpage-content-cutting-off-safari/
2
2
275
1w
Application Hangs with Nested LazyVStack When Accessibility Inspector is Active
Description I've encountered a consistent hang/freeze issue in SwiftUI applications when using nested LazyVStack containers with Accessibility Inspector (simulator) or VoiceOver (physical device) enabled. The application becomes completely unresponsive and must be force-quit. Importantly, this hang occurs in a minimal SwiftUI project with no third-party dependencies, suggesting this is a framework-level issue with the interaction between SwiftUI's lazy view lifecycle and the accessibility system. Reproduction Steps I've created a minimal reproduction project available here: https://github.com/pendo-io/SwiftUI_Hang_Reproduction To Reproduce: Create a SwiftUI view with the following nested LazyVStack structure: struct NestedLazyVStackView: View { @State private var outerSections: [Int] = [] @State private var innerRows: [Int: [Int]] = [:] var body: some View { ScrollView { LazyVStack(alignment: .leading, spacing: 24) { ForEach(outerSections, id: \.self) { section in VStack(alignment: .leading, spacing: 8) { Text("Section #\(section)") // Nested LazyVStack LazyVStack(alignment: .leading, spacing: 2) { ForEach(innerRows[section] ?? [], id: \.self) { row in Text("Section #\(section) - Row #\(row)") .onAppear { // Load more data when row appears loadMoreInner(section: section) } } } } .onAppear { // Load more sections when section appears loadMoreOuter() } } } } } } Enable Accessibility Inspector in iOS Simulator: Xcode → Open Developer Tool → Accessibility Inspector Select your running simulator Enable Inspection mode (eye icon) Navigate to the view and start scrolling Result: The application hangs and becomes unresponsive within a few seconds of scrolling Expected Behavior The application should remain responsive when Accessibility Inspector or VoiceOver is enabled, allowing users to scroll through nested lazy containers without freezing. Actual Behavior The application freezes/hangs completely CPU usage may spike The app must be force-quit to recover The hang occurs consistently and is reproducible Workaround 1: Replace inner LazyVStack with VStack LazyVStack { ForEach(...) { section in VStack { // ← Changed from LazyVStack ForEach(...) { row in ... } } } } Workaround 2: Embed in TabView TabView { NavigationStack { NestedLazyVStackView() // ← Same nested structure, but no hang } .tabItem { ... } } Interestingly, wrapping the entire navigation stack in a TabView prevents the hang entirely, even with the nested LazyVStack structure intact. Questions for Apple Is there a known issue with nested LazyVStack containers and accessibility traversal? Why does wrapping the view in a TabView prevent the hang? Are there recommended patterns for using nested lazy containers with accessibility support? Is this a timing issue, a deadlock, or an infinite loop in the accessibility system? Why that happens? Reproduction Project A complete, minimal reproduction project is available at: https://github.com/pendo-io/SwiftUI_Hang_Reproduction
5
0
495
1w
iOS 26: Enabling "Reduce Transparency" causes a persistent white bar where the tab bar was hidden, blocking user interaction
Hi everyone, We're experiencing a bug on iOS 26 that only occurs when the user has Reduce Transparency enabled in Accessibility settings. App structure: Our app uses a TabView with a standard tab bar. Inside each tab, we use a NavigationStack. The tab bar is visible on root-level screens, and hidden on all pushed destinations using: .toolbar(.hidden, for: .tabBar) The problem: On iOS 26 with Reduce Transparency off (Liquid Glass active) — everything works correctly. The tab bar hides as expected. On iOS 26 with Reduce Transparency on — a white bar appears at the bottom of the screen in every place where the tab bar is hidden. This white bar: Overlaps content at the bottom of the screen. Blocks scroll, tap, and all user interactions in that area. We also tried: .toolbarBackground(.hidden, for: .tabBar) Removing all custom UITabBarAppearance configuration The only workaround we found is setting UIDesignRequiresCompatibility = YES in Info.plist, which reverts the entire app to the pre-iOS 26 design — not a viable long-term solution. What can we do? Thanks in advance.
Replies
2
Boosts
0
Views
135
Activity
18h
NSFileSandboxingRequestRelatedItemExtension: Failed to issue extension
Hi there, I have an SwiftUI app that opens a user selected audio file (wave). For each audio file an additional file exists containing events that were extracted from the audio file. This additional file has the same filename and uses the extension bcCalls. I load the audio file using FileImporter view modifier and within access the audio file with a security scoped bookmark. That works well. After loading the audio I create a CallsSidecar NSFilePresenter with the url of the audio file. I make the presenter known to the NSFileCoordinator and upon this add it to the FileCoordinator. This fails with NSFileSandboxingRequestRelatedItemExtension: Failed to issue extension for; Error Domain=NSPOSIXErrorDomain Code=3 "No such process" My Info.plist contains an entry for the document with NSIsRelatedItemType set to YES I am using this kind of FilePresenter code in various live apps developed some years ago. Now when starting from scratch on a fresh macOS26 system with most current Xcode I do not manage to get it running. Any ideas welcome! Here is the code: struct ContentView: View { @State private var sonaImg: CGImage? @State private var calls: Array<CallMeasurements> = Array() @State private var soundContainer: BatSoundContainer? @State private var importPresented: Bool = false var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") if self.sonaImg != nil { Image(self.sonaImg!, scale: 1.0, orientation: .left, label: Text("Sonagram")) } if !(self.calls.isEmpty) { List(calls) {aCall in Text("\(aCall.callNumber)") } } Button("Load sound file") { importPresented.toggle() } } .fileImporter(isPresented: $importPresented, allowedContentTypes: [.audio, UTType(filenameExtension: "raw")!], onCompletion: { result in switch result { case .success(let url): let gotAccess = url.startAccessingSecurityScopedResource() if !gotAccess { return } if let soundContainer = try? BatSoundContainer(with: url) { self.soundContainer = soundContainer self.sonaImg = soundContainer.overviewSonagram(expectedWidth: 800) let callsSidecar = CallsSidecar(withSoundURL: url) let data = callsSidecar.readData() print(data) } url.stopAccessingSecurityScopedResource() case .failure(let error): // handle error print(error) } }) .padding() } } The file presenter according to the WWDC 19 example: class CallsSidecar: NSObject, NSFilePresenter { lazy var presentedItemOperationQueue = OperationQueue.main var primaryPresentedItemURL: URL? var presentedItemURL: URL? init(withSoundURL audioURL: URL) { primaryPresentedItemURL = audioURL presentedItemURL = audioURL.deletingPathExtension().appendingPathExtension("bcCalls") } func readData() -> Data? { var data: Data? var error: NSError? NSFileCoordinator.addFilePresenter(self) let coordinator = NSFileCoordinator.init(filePresenter: self) NSFileCoordinator.addFilePresenter(self) coordinator.coordinate(readingItemAt: presentedItemURL!, options: [], error: &error) { url in data = try! Data.init(contentsOf: url) } return data } } And from Info.plist <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeExtensions</key> <array> <string>bcCalls</string> </array> <key>CFBundleTypeName</key> <string>bcCalls document</string> <key>CFBundleTypeRole</key> <string>None</string> <key>LSHandlerRank</key> <string>Alternate</string> <key>LSItemContentTypes</key> <array> <string>com.apple.property-list</string> </array> <key>LSTypeIsPackage</key> <false/> <key>NSIsRelatedItemType</key> <true/> </dict> <dict> <key>CFBundleTypeExtensions</key> <array> <string>wav</string> <string>wave</string> </array> <key>CFBundleTypeName</key> <string>Windows wave</string> <key>CFBundleTypeRole</key> <string>Editor</string> <key>LSHandlerRank</key> <string>Alternate</string> <key>LSItemContentTypes</key> <array> <string>com.microsoft.waveform-audio</string> </array> <key>LSTypeIsPackage</key> <integer>0</integer> <key>NSDocumentClass</key> <string></string> </dict> </array> Note that BatSoundContainer is a custom class for loading audio of various undocumented formats as well as wave, Flac etc. and this is working well displaying a sonogram of the audio. Thx, Volker
Replies
12
Boosts
0
Views
491
Activity
1d
manageSubscriptionsSheet resulting in "No connection"
I have an iOS app (SwiftUI) that includes recurring subscriptions. To allow users to manage their subscriptions I have implemented manageSubscriptionsSheet according to apple documentation. When I published the app last year for iOS17 and iOS18 this was working well. Now I have gotten a user report that this features yields No connection error instead of the abonnements on iOS26. I have tested on my iPad running iOS 26 as well as on the simulator with iOS 26 and 18. In all cases I get the error. I can press Retry in the dialog and am prompted for AppStore credentials After entering them, again the same error. I can not find a single hint on why and how to fix it. Best wishes, Volker
Replies
2
Boosts
0
Views
43
Activity
1d
Reality View Preserves Camera Transform when toggling Virtual & Spatial Tracking modes
When switching from RealityView’s .spatialTracking camera mode to .virtual camera mode, the camera’s orientation relative to the scene is preserved permanently with no way to reset to default World-Up orientation. Since .spatialTracking’s camera mode will always have a non-default orientation, switching to .virtual camera mode ensures that the cameras’s ‘UP’ direction will never match the device display’s ‘UP’ direction as is default. This is especially noticeable when using .orbit camera controls, as the orbit’s UP direction matches the scene, not camera, and all rotation directions give unexpected results. Expected: When setting virtual camera mode after using spatialTracking camera mode, either 1. The Virtual Camera orientation returns to default (world up). Or 2. A 'content.camera.resetOrientation()' call is made available which resets the RealityView camera to default orientation. Reality: Switching from .spatialTracking -> .virtual camera mode permanently locks the .virtual camera’s orientation the final frame of the .spatialTracking camera’s rotation (relative to the RealityView content scene). One imperfect workaround is to reset / rebuild the entire RealityView after changing modes (by resetting .id() or otherwise. This is not ideal as it causes everything inside the make closure to rerun, which not only is a performance & time cost, visually incurs a flicker and can also be problematic with managing increasingly complicated views. Another imperfect alternative is to use more than one RealityView - which is not ideal as it incurs double the base ram usage, significantly increases code, and seemingly goes against the intent of being able to change the camera .virtual/.spatatialTracking mode at will. Code Sample: import SwiftUI import RealityKit struct RKSpatialVirtualToggle: View { @State var showAR: Bool = false var body: some View { RealityView { content in let cube = ModelEntity(mesh: .generateBox(size: 0.25), materials: [SimpleMaterial()]) cube.position.z = -1 content.add(cube) content.camera = showAR ? .spatialTracking : .virtual content.cameraTarget = cube } update: { content in content.camera = showAR ? .spatialTracking : .virtual } .realityViewCameraControls(.orbit) VStack{ Spacer() Button("Toggle AR"){ showAR.toggle() } .buttonStyle(.borderedProminent) } } } Xcode Version: Version 26.0 (17A324) iOS Version: iOS 26.5 (23F75) Tested on devices, iPhone 12 Pro, iPhone 15 Pro
Replies
1
Boosts
0
Views
37
Activity
1d
SecureField dots invisible in dark mode when iOS suggests and fills a strong password
I am using SwiftUI's native SecureField. When a user types their password manually, the dots render correctly in both light and dark mode. However, when iOS suggests and autofills a strong generated password, the dots become invisible in dark mode. Switching to light mode shows that they are there. Is there a supported way to force SecureField to re-render its secure entry dots correctly after iOS fills in a strong generated password in dark mode? import SwiftUI let warmMustard = Color(red: 0.780, green: 0.659, blue: 0.290) let lightText = Color(red: 0.973, green: 0.961, blue: 0.933) let darkText = Color(red: 0.118, green: 0.118, blue: 0.118) struct SecureFieldTestView: View { @Environment(\.colorScheme) var colorScheme @State private var username = "" @State private var password = "" @State private var confirmPassword = "" var body: some View { ZStack { Color(colorScheme == .dark ? UIColor.black : UIColor.white) .ignoresSafeArea() VStack(spacing: 20) { Text("Dark mode dot reproduction") .foregroundColor(colorScheme == .dark ? .white : .black) TextField("Username", text: $username) .textContentType(.username) .autocorrectionDisabled() .textInputAutocapitalization(.never) .padding() .background(colorScheme == .dark ? Color.black : Color.white) .cornerRadius(8) .foregroundColor(colorScheme == .dark ? .white : .black) .overlay(RoundedRectangle(cornerRadius: 8).stroke(warmMustard, lineWidth: 2)) SecureField("Password", text: $password) .textContentType(.newPassword) .padding() .background(colorScheme == .dark ? Color.black : Color.white) .cornerRadius(8) .foregroundColor(colorScheme == .dark ? .white : .black) .overlay(RoundedRectangle(cornerRadius: 8).stroke(warmMustard, lineWidth: 2)) SecureField("Confirm Password", text: $confirmPassword) .textContentType(.newPassword) .padding() .background(colorScheme == .dark ? Color.black : Color.white) .cornerRadius(8) .foregroundColor(colorScheme == .dark ? .white : .black) .overlay(RoundedRectangle(cornerRadius: 8).stroke(warmMustard, lineWidth: 2)) } .padding(.horizontal, 32) } } } #Preview { SecureFieldTestView() }
Replies
2
Boosts
0
Views
69
Activity
1d
How to set the Locale.current to be same as the Environment locale?
I have this code As you can see, the locale of the Environment is different from the Locale given by .current. This is a problem for me because I have code that uses String(localized:) and AttributedString. I would like to be able to preview them with the locale I set in the Environment without any additional work on my part. I assumed these Apis would use the locale set by the environment but no, it uses the locale as decided by the schema used to build the preview app. The current solution I have is to manually change the App Language in the Preview's scheme to be whatever I need to correctly localize the language in Preview.
Replies
1
Boosts
0
Views
57
Activity
1d
How to set custom height for keyboard extension without resize flicker?
Description I'm developing a custom keyboard extension using UIInputViewController and need to set a specific height of 268 points. The keyboard functions correctly, but there's a visible flicker and resize animation during launch that I cannot eliminate. The Problem When the keyboard launches, iOS provides incorrect heights before settling on the correct one. At launch, the view starts at 0×0. Around 295ms later, iOS sets the frame to 440×956 which is full screen height and wrong. Around 373ms, iOS changes it to 440×452 which is still wrong. Finally around 390ms, iOS settles at 440×268 which matches our constraint. This causes visible flicker as the view resizes three times rapidly. The keyboard appears to shrink from full screen down to the correct height, and users can clearly see this animation happening. What I've Tried I've tried adding a height constraint on self.view which gives me the correct height but causes the visible flicker. I created a custom UIInputView subclass and overrode intrinsicContentSize to return my desired height. iOS completely ignores this and gives random heights like 471pt, 680pt, or 956pt instead. I set allowsSelfSizing to true on my UIInputView subclass. iOS ignores this property. I set preferredContentSize on the view controller. iOS ignores this as well. I tried adding the constraint in viewDidAppear instead of viewDidLoad, thinking iOS might have settled by then. It still causes flicker. I overrode the frame and bounds setters on my UIInputView to clamp the height to my desired value. iOS bypasses these overrides somehow. I overrode layoutSubviews to force the correct height after the super call. iOS still applies its own height. Specific Question What is the correct API or technique to specify a keyboard extension's height that iOS will respect immediately upon launch, without triggering the resize animation sequence? Other third-party keyboards like Grammarly and SwiftKey appear to have solved this problem. Their keyboards appear at the correct height without any visible flicker. How do they achieve this? Expected Outcome The keyboard should appear at 268pt height on the first frame with no visible resize animation. Steps to Reproduce Create a new iOS App project in Xcode and add a Keyboard Extension target. In KeyboardViewController.swift, add a height constraint in viewDidLoad: override func viewDidLoad() { super.viewDidLoad() let heightConstraint = view.heightAnchor.constraint(equalToConstant: 268) heightConstraint.priority = .defaultHigh heightConstraint.isActive = true let label = UILabel() label.text = "Demo Keyboard" label.textAlignment = .center label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: view.centerXAnchor), label.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } Build and run on a physical device. Enable the keyboard in Settings, then General, then Keyboard, then Keyboards. Open any app with a text field and switch to the custom keyboard using the globe button. Observe the height changing from around 956pt to 452pt to 268pt with visible animation. Environment iOS 17 and iOS 18 and 26.2, Xcode 16 and Xcode 26, affects all iPhone models tested, reproducible on both simulator and physical device.
Replies
1
Boosts
3
Views
206
Activity
1d
SwiftData 'simple' migration failing
This is a long post, so let me start with a summary: I am attempting to implement what "ought to be" a simple SwiftData migration, and am receiving the following fatal error from the ModelContainer initializer: NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." The crash occurs both in the Simulator and on a physical device. Both the original schema and the new schema load and run as expected if loaded from scratch — so I conclude the Models are OK; it is the migration from the original schema to the new schema which is the issue. I have reported this as FB22652791 and Technical Incident Case # 19893980. I have two model projects available — one contrived, the other using my actual SwiftData models. Now the Details I am developing a SwiftUI/SwiftData app. I am (currently) using Xcode 26.5-beta-3. I set up an alpha-test build using the following approach: public class DatabaseSchema { public let dbSchema: Schema = Schema([ Model1.self, ... , Model16.self ], version: Schema.Version(0, 9, 0)) public var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false) do { container = try ModelContainer(for: dbSchema, migrationPlan: nil, configurations: [modelConfiguration]) } catch { fatalError("Failed to creae model conainer") } return container } This defines database version 0.9. For version 1.0, I made three changes to the database: added an attribute of type String to Model2. added three attributes of type [Struct], where Struct conforms to Codable, Equatable and Hashable to Model3, and added a new model (which I'll call Model17) I define two schemas: public enum Schema090: VersionedSchema { public static var versionIdentifier = Schema.Version(0, 9, 0) public static var models: [any PersistentModel.Type] = [ Model1.self, Schema090.Model2.self, Schema090.Model3.self, ... ] } and public enum Schema100: VersionedSchema { public static var versionIdentifier = Schema.Version(1, 0, 0) public static var models: [any PersistentModel.Type] = [ Model1.swift, Schema100.Model2.self, Schema100.Model3.self, ..., Model16.self, Schema100.Model17.self ] } For models that changed, I use the following approach: public typealias Model3 = Schema100.Model3 extension Schema090 { @Model final class Model3 { ... } public init() { ... } } extension Schema100 { @Model final class Model3 { ... <added attributes, initialized> } public init() { ... } } The DatabaseSchema class was modified as follows: public class DatabaseSchema { public let dbSchema: Schema = Schema([ Model1.self, Schema100.Model2.self, Schema100.Model3.self, ... , Model16.self, Schema100.Model17.self ], version: Schema.Version(1, 0, 0)) public var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false) do { container = try ModelContainer(for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) } catch { fatalError("Failed to creae model conainer") } return container } where the migration plan is the trivial custom migration that makes sure that all added attributes of existing records are properly initialized. enum MigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] = [ Schema090.self, Schema100.self ] static var stages: [MigrationStage] = [version090ToVersion100] static let version090ToVersion100 = MigrationStage(fromVersion: Schema090.self, toVersion: Schema100.self, willMigrate: { _ in }, didMigrate: { context in let models = try context.fetch( FetchDescriptor<Schema100.Model3>()) for model in models { < initial the added attributes > { try context.save() }) } This is all simple stuff. Nothing particularly fancy here. But running this code always crashes in the ModelContainer initializer. In my two sample projects, I get two different error messages — in the contrived example, the error message is Code=134110 "An error occurred during persistent store migration." reason=Cannot migrate store in-place: Validation error missing attribute values on mandatory destination attribute, ... and in the sample project that uses my actual data model, I get NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." My Thoughts Since obviously most folks are doing SwiftData migrations without the problems I am experiencing, the obvious possibilities are I'm doing something stupid that I just don't see. There is a problem because the original schema was given a version value of Schema.Version(0, 9, 0). (i.e., major version number was 0) There is a problem because I am adding an attribute of type [Struct] where Struct is Codable, Hashable, and Equatable. I.e., migration isn't working properly with attributes which are stored as their codable representations. Or maybe something else? In any case, any help you can offer would be greatly appreciated.
Replies
7
Boosts
0
Views
592
Activity
1d
AttributedString Localization does not seem to work
I have this code struct TestAppleSuggestion: View { @Environment(\.locale) var locale: Locale var body: some View { VStack { VStack { Text("locale: \(locale.identifier)") Text(AttributedString(localized: LocalizedStringResource( "welcome", locale: locale ))) Text(AttributedString(localized: "welcome", locale: locale )) } } } } #Preview { TestAppleSuggestion().environment(\.locale, Locale(identifier: "fr-CA")) } Heres What I see in SwiftUi Previews The Localization is working for the LocalizedStringResource but not to the AttributedString. Why?
Replies
3
Boosts
0
Views
166
Activity
1d
Swift compiler error when using DeclaredAgeRange with swift 6
I added a dummy view - copy paste directly from the Apple Developer Documentation, in a swift package using swift 6 and got concurency error. The fix is to switch to swift 5
Replies
2
Boosts
0
Views
48
Activity
2d
NavigationSplitView no longer pops back to the root view when selection = nil in iOS 26.4 (with a nested TabView)
In iOS 26.4 (iPhone, not iPad), when a NavigationSplitView is combined with a nested TabView, it no longer pops back to the root sidebar view when the List selection is set to nil. This has been working fine for at least a few years, but has just stopped working in iOS 26.4. Here's a minimal working example: import SwiftUI struct ContentView: View { @State var articles: [Article] = [Article(articleTitle: "Dog"), Article(articleTitle: "Cat"), Article(articleTitle: "Mouse")] @State private var selectedArticle: Article? = nil var body: some View { NavigationSplitView { TabView { Tab { List(articles, selection: $selectedArticle) { article in Button { selectedArticle = article } label: { Text(article.title) } } } label: { Label("Explore", systemImage: "binoculars") } } } detail: { Group { if let selectedArticle { Text(selectedArticle.title) } else { Text("No selected article") } } .navigationBarBackButtonHidden(true) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Close", systemImage: "xmark") { selectedArticle = nil } } } } } } struct Article: Identifiable, Hashable { let id: String let title: String init(articleTitle: String) { self.id = articleTitle self.title = articleTitle } } First, I'm aware that nesting a TabView inside a NavigationSplitView is frowned upon: Apple seems to prefer NavigationSplitView nested inside a Tab. However, for my app, that leads to a very confusing user experience. Users quickly get lost because they end up with different articles open in different tabs and it doesn't align well with my core distinction between two "modes": article selection mode and article reading mode. When the user is in article selection mode (sidebar view), they can pick between different ways of selecting an article (Explore, Bookmarks, History, Search), which are implemented as "tabs". When they pick an article from any tab they jump into article reading mode (the detail view). Second, I'm using .navigationBarBackButtonHidden(true) to remove the auto back button that pops back to the sidebar view. This button does still work in iOS 26.4, even with the nested TabView. However, I can't use the auto back button because my detail view is actually a WebView with its own back/forward logic and UI. Therefore, I need a separate close button to exit from the detail view. My close button sets selectedArticle to nil, which (pre-iOS 26.4) would trigger the NavigationSplitView to pop back to the sidebar view. For some reason, in iOS 26.4 the NavigationSplitView doesn't seem to bind correctly to the List's selection parameter, specifically when there's a TabView nested between them. Or, rather, it binds, but fails to pop back when selection becomes nil. One option is to replace NavigationSplitView with NavigationStack (on iPhone). NavigationStack still works with a nested TabView, but it creates other downstream issues for me (as well as forcing me to branch for iPhone and iPad), so I'd prefer to continue using NavigationSplitView. Does anyone have any ideas about how to work around this problem? Is there some way of explicitly telling NavigationSplitView to pop back to the sidebar view on iPhone? (I've tried setting the column visibility but nothing seems to work). Thanks for any help!
Replies
1
Boosts
1
Views
166
Activity
3d
Is it possible to focus a non-textField on iPadOS in SwiftUI?
I would like to implement a focus-based Menu-Bar command in my SwiftUI iPadOS app, or react to key command while certain elements are focused. Traditionally, this requires using @FocusedValue and focusable() and focused, however, it appears that setting a @FocusState on macOS will work, but setting a @FocusState on iPadOS will never work. How can this API work and support MenuBar commands and keyboard inputs? It kind of has an accessibility impact as well. Not all users are going to know, or want to turn on "full keyboard control" for basic interactions. Here's a small sample that doesn't appear to focus on iPadOS: struct FocusableTestView: View { @FocusState private var isRectFocused: Bool var body: some View { VStack { // This text field should focus the custom input when pressing return: TextField("Enter text", text: .constant("")) .textFieldStyle(.roundedBorder) .onSubmit { isRectFocused = true } .onKeyPress(.return) { isRectFocused = true return .handled } // This custom "input" should focus itself when tapped: Rectangle() .fill(isRectFocused ? Color.accentColor : Color.gray.opacity(0.3)) .frame(width: 100, height: 100) .overlay( Text(isRectFocused ? "Focused" : "Tap me") ) .focusable(true) .focused($isRectFocused) .onTapGesture { isRectFocused = true print("Focused rectangle") } // The focus should be able to be controlled externally: Button("Toggle Focus") { isRectFocused.toggle() } .buttonStyle(.bordered) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) } }
Replies
0
Boosts
0
Views
149
Activity
6d
Focusable doesn't work on iPad with external keyboard
I have a custom input view in my app which is .focusable(). It behaves similar to a TextField, where it must be focused in order to be used. This works fine on all platforms including iPad, except when when an external keyboard is connected (magic keyboard), in which case it can't be focused anymore and becomes unusable. Is there a solution to this, or a workaround? My view is very complex, so simple solutions like replacing it with a native view isn't possible, and I must be able to pragmatically force it to focus. Here's a very basic example replicating my issue. Non of the functionality works when a keyboard is connected: struct FocusableTestView: View { @FocusState private var isRectFocused: Bool var body: some View { VStack { // This text field should focus the custom input when pressing return: TextField("Enter text", text: .constant("")) .textFieldStyle(.roundedBorder) .onSubmit { isRectFocused = true } .onKeyPress(.return) { isRectFocused = true return .handled } // This custom "input" should focus itself when tapped: Rectangle() .fill(isRectFocused ? Color.accentColor : Color.gray.opacity(0.3)) .frame(width: 100, height: 100) .overlay( Text(isRectFocused ? "Focused" : "Tap me") ) .focusable(true, interactions: .edit) .focused($isRectFocused) .onTapGesture { isRectFocused = true print("Focused rectangle") } // The focus should be able to be controlled externally: Button("Toggle Focus") { isRectFocused.toggle() } .buttonStyle(.bordered) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) } }
Replies
2
Boosts
0
Views
291
Activity
6d
Is updateUIViewController always called immediately after makeUIViewController?
I'm in the unenviable position of needing the current UIViewController to keep an external library happy. Essentially, I need to do this in SwiftUI: import LibraryOutOfMyControl ViewControllerReader { viewController in Button("Action") { LibraryOutOfMyControl.action(with: viewController) } } My simple attempt below functions correctly but I'm relying on makeUIViewController always being immediately followed by updateUIViewController. Is the a reasonable assumption or should I set everything up assuming updateUIViewController might never be called? struct ViewControllerReader<Content>: UIViewControllerRepresentable where Content: View { @ViewBuilder var content: (UIViewController) -> Content func makeUIViewController(context: Context) -> UIHostingController<Content> { UIHostingController(rootView: content(UIViewController())) } func updateUIViewController(_ uiViewController: UIHostingController<Content>, context: Context) { uiViewController.rootView = content(uiViewController) uiViewController.view.isUserInteractionEnabled = context.environment.isEnabled } func sizeThatFits(_ proposal: ProposedViewSize, uiViewController: UIHostingController<Content>, context: Context) -> CGSize? { uiViewController.sizeThatFits(in: proposal.replacingUnspecifiedDimensions()) } }
Replies
0
Boosts
0
Views
106
Activity
1w
SwiftUI navigation bar button color changes depending on whether the root view is a ScrollView or VStack
I have a SwiftUI view inside a NavigationStack with a custom navigation bar background color. I want the navigation bar buttons to have a consistent color throughout the app. The issue is that the navigation bar button color changes depending on the first/root view in the body. When the root view is a ScrollView var body: some View { ScrollView { // content } .toolbarBackground(Color(red: 0.02, green: 0.27, blue: 0.13), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } The navigation bar buttons appear white. However, if I replace the ScrollView with a VStack, while keeping the same modifiers, the navigation bar buttons appear black: var body: some View { VStack { // content } .toolbarBackground(Color(red: 0.02, green: 0.27, blue: 0.13), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } The navigation bar buttons appear black. How can I make the navigation bar buttons stay the same colour in both cases?
Replies
1
Boosts
0
Views
184
Activity
1w
.disabled() doesn't VISUALLY disable buttons inside ToolbarItem on iOS 26 devices
[Also submitted as FB19313064] The .disabled() modifier doesn't visually disable buttons inside a ToolbarItem container on iOS 26.0 (23A5297i) devices. The button looks enabled, but tapping it doesn't trigger the action. When deployment target is lowered to iOS 18 and deployed to an iOS 18 device, it works correctly. It still fails on an iOS 26 device, even with an iOS 18-targeted build. This occurs in both the Simulator and on a physical device. Screen Recording Code struct ContentView: View { @State private var isButtonDisabled = false private var osTitle: String { let version = ProcessInfo.processInfo.operatingSystemVersion return "iOS \(version.majorVersion)" } var body: some View { NavigationStack { VStack { Button("Body Button") { print("Body button tapped") } .buttonStyle(.borderedProminent) .disabled(isButtonDisabled) Toggle("Disable buttons", isOn: $isButtonDisabled) Spacer() } .padding() .navigationTitle("Device: \(osTitle)") .navigationBarTitleDisplayMode(.large) .toolbar { ToolbarItem { Button("Toolbar") { print("Toolbar button tapped") } .buttonStyle(.borderedProminent) .disabled(isButtonDisabled) } } } } }
Replies
8
Boosts
3
Views
734
Activity
1w
SwiftUI Button with Image view label has smaller hit target
[Also submitted as FB20213961] SwiftUI Button with a label: closure containing only an Image view has a smaller tap target than buttons created with a Label or the convenience initializer. The hit area shrinks to the image bounds instead of preserving the standard minimum tappable size. SCREEN RECORDING On a physical device, the difference is obvious—it’s easy to miss the button. Sometimes it even shows the button-tapped bounce animation but doesn’t trigger the action. SYSTEM INFO Xcode Version 26.0 (17A321) macOS 15.6.1 (24G90) iOS 26.0 (23A340) SAMPLE CODE The following snippet shows the difference in hit targets between the convenience initializer, a Label, and an Image (the latter two in a label: closure). // ✅ Hit target is entire button Button("Button 1", systemImage: "1.square.fill") { print("Button 1 tapped") } // ✅ Hit target is entire button Button { print("Button 2 tapped") } label: { Label("Button 2", systemImage: "2.square.fill") } // ❌ Hit target is smaller than button Button { print("Button 3 tapped") } label: { Image(systemName: "3.square.fill") }
Replies
6
Boosts
4
Views
482
Activity
1w
Changing systemImage value for Image, logs "fopen failed for data file".
I'm getting a log error and a slight delay in the UI when displaying a system image that changes at the end of a sequence. I'm using a ternary operator to determine the image; the fact that the image changes seem to be the issue, rather than the value itself. The issue only occurs for a newly installed app, and not when the app is rerun. (I'm using similar code to display an onboarding sequence after installation.) This happens on device (iphone 15 pro v25.6) and simulator (iphone 17 pro v25.6 and iphone 16 pro v18.5); xcode 26.5 (17F42). Console errors (device and iphone 17 simulator): fopen failed for data file: errno = 2 (No such file or directory) fopen failed for data file: errno = 2 (No such file or directory) Repro Code: import SwiftUI struct ContentView: View { // NOTE: error only occurs with new install. @State private var currentItem = 0 @State private var totalItems: Int = 4 var body: some View { VStack(spacing: 0) { Spacer() Text("totalItems: \(totalItems)") TabView(selection: $currentItem) { ForEach(0...totalItems, id: \.self) { item in Text("\(item) ~ \(currentItem)") .tag(item) } } //TV .tabViewStyle(.page(indexDisplayMode: .never)) .frame(height: 200) Button { if currentItem < totalItems { currentItem += 1 currentItem = min(totalItems, currentItem) } } label: { let imgString: String = (currentItem == totalItems ? "arrowshape.turn.up.right" : "arrowshape.right") // error // let imgString: String = ((currentItem == totalItems) ? "x.circle" : "smallcircle.filled.circle") // error // let imgString: String = "smallcircle.filled.circle" // no error // let imgString: String = "x.circle" // no error Text("\(imgString)") // if only print text, no error, so issue seems to be with Image. Image(systemName: imgString) } Spacer() } } } Click through the button sequence to see issue at end of sequence. Uncomment the various imgString lines to see indicated differences in behavior. Need to delete app each time to repro issue. Running in simulator on iphone 16 Pro iOS 18.5 has slightly different error messages: fopen failed for data file: errno = 2 (No such file or directory) Errors found! Invalidating cache... fopen failed for data file: errno = 2 (No such file or directory) Errors found! Invalidating cache...
Replies
1
Boosts
0
Views
65
Activity
1w
iOS 26 rendering gap on scroll surfaces — lower scroll view does not render
On iOS 26 (26.0–26.5), a rectangular region in the lower half of the screen sometimes does not render while the content underneath remains laid out and interactive — scrolling works, hit testing succeeds, and rows visibly emerge from behind the floating tab bar as you scroll. This is a render-server / compositor gap, not a layout or safe-area issue. We see it on both UIKit and SwiftUI scroll surfaces inside the same UITabBarController: UIKit: UICollectionView with UICollectionViewFlowLayout (sectionInsetReference = .fromSafeArea) SwiftUI: List(.plain) nested in TabView(.page) inside a UIHostingController Confirmed on iPhone 16 Pro, iPhone 17 Pro, iPhone 13 Pro Max. Community threads (linked below) report the same symptom in Messages, Notes, Safari, Mail, and the App Store. Questions for Apple Is this acknowledged as an OS-level regression, and is a fix targeted for an upcoming iOS 26.x release? Is there a deterministic repro? We've tried background/foreground cycles, push notifications mid-scroll, tab switches during inertia, lock/unlock, orientation flips, simulated memory warnings, layout-invalidation storms, and trait-collection cycles — none reliably trigger it on our test devices. Is there a developer-side mitigation (e.g. avoiding specific UIVisualEffectView / Glass configurations, opting out of a rendering optimization) until a system fix lands? Is there a runtime signal on CALayer or UIScrollView we can inspect to detect this gap state and force a recovery (tile redraw, backing-store discard, etc.)? Notes We cannot reproduce locally. Affected users hit it organically; once it appears it persists across re-layout until the view controller is torn down. Community reports consistently mention Reduce Transparency being enabled on affected devices, and toggling it off clears the issue for many. In our own testing, RT alone is not sufficient to trigger the bug — it appears to be a contributing condition rather than the trigger. References: Apple Discussions: https://discussions.apple.com/thread/256182149 Reddit r/ios (multiple system apps): https://www.reddit.com/r/ios/comments/1nlzn7f/some_apps_cutting_off_half_the_display/ https://www.idownloadblog.com/2026/03/23/webpage-content-cutting-off-safari/
Replies
2
Boosts
2
Views
275
Activity
1w
Application Hangs with Nested LazyVStack When Accessibility Inspector is Active
Description I've encountered a consistent hang/freeze issue in SwiftUI applications when using nested LazyVStack containers with Accessibility Inspector (simulator) or VoiceOver (physical device) enabled. The application becomes completely unresponsive and must be force-quit. Importantly, this hang occurs in a minimal SwiftUI project with no third-party dependencies, suggesting this is a framework-level issue with the interaction between SwiftUI's lazy view lifecycle and the accessibility system. Reproduction Steps I've created a minimal reproduction project available here: https://github.com/pendo-io/SwiftUI_Hang_Reproduction To Reproduce: Create a SwiftUI view with the following nested LazyVStack structure: struct NestedLazyVStackView: View { @State private var outerSections: [Int] = [] @State private var innerRows: [Int: [Int]] = [:] var body: some View { ScrollView { LazyVStack(alignment: .leading, spacing: 24) { ForEach(outerSections, id: \.self) { section in VStack(alignment: .leading, spacing: 8) { Text("Section #\(section)") // Nested LazyVStack LazyVStack(alignment: .leading, spacing: 2) { ForEach(innerRows[section] ?? [], id: \.self) { row in Text("Section #\(section) - Row #\(row)") .onAppear { // Load more data when row appears loadMoreInner(section: section) } } } } .onAppear { // Load more sections when section appears loadMoreOuter() } } } } } } Enable Accessibility Inspector in iOS Simulator: Xcode → Open Developer Tool → Accessibility Inspector Select your running simulator Enable Inspection mode (eye icon) Navigate to the view and start scrolling Result: The application hangs and becomes unresponsive within a few seconds of scrolling Expected Behavior The application should remain responsive when Accessibility Inspector or VoiceOver is enabled, allowing users to scroll through nested lazy containers without freezing. Actual Behavior The application freezes/hangs completely CPU usage may spike The app must be force-quit to recover The hang occurs consistently and is reproducible Workaround 1: Replace inner LazyVStack with VStack LazyVStack { ForEach(...) { section in VStack { // ← Changed from LazyVStack ForEach(...) { row in ... } } } } Workaround 2: Embed in TabView TabView { NavigationStack { NestedLazyVStackView() // ← Same nested structure, but no hang } .tabItem { ... } } Interestingly, wrapping the entire navigation stack in a TabView prevents the hang entirely, even with the nested LazyVStack structure intact. Questions for Apple Is there a known issue with nested LazyVStack containers and accessibility traversal? Why does wrapping the view in a TabView prevent the hang? Are there recommended patterns for using nested lazy containers with accessibility support? Is this a timing issue, a deadlock, or an infinite loop in the accessibility system? Why that happens? Reproduction Project A complete, minimal reproduction project is available at: https://github.com/pendo-io/SwiftUI_Hang_Reproduction
Replies
5
Boosts
0
Views
495
Activity
1w