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

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.
0
0
11
1h
Popover in Toolbar Causes Crash in Catalyst App on macOS 26
Hi everyone, I’ve encountered an issue where using a popover inside the toolbar of a Catalyst app causes a crash on macOS 26 beta 5 with Xcode 26 beta 5. Here’s a simplified code snippet: import SwiftUI struct ContentView: View { @State private var isPresentingPopover = false var body: some View { NavigationStack { VStack { } .padding() .toolbar { ToolbarItem { Button(action: { isPresentingPopover.toggle() }) { Image(systemName: "bubble") } .popover(isPresented: $isPresentingPopover) { Text("Hello") .font(.largeTitle) .padding() } } } } } } Steps to reproduce: Create a new iOS app using Xcode 26 beta 5. Enable Mac Catalyst (Match iPad). Add the above code to show a Popover from a toolbar button. Run the app on macOS 26, then click the toolbar button. The app crashes immediately upon clicking the toolbar button. Has anyone else run into this? Any workarounds or suggestions would be appreciated! Thanks!
5
1
203
12h
SwiftUI iOS 26 .safeAreaBar issue with large navigation title
I have some really straight forward code in a sample project. For some reason when the app launches the title is blurred obscured by scrolledgeeffect blur. If I scroll down the title goes small as it should do and all looks fine. If I scroll back to the top, just before it reaches the top the title goes large and it looks correct, but once it actually reaches/snaps to the top, is then incorrectly blurs again. Is there anything obvious I'm doing wrong? Is this a bug? struct ContentView: View { var body: some View { NavigationStack { ScrollView { VStack { Rectangle().fill(Color.red.opacity(0.2)).frame(height: 200) Rectangle().frame(height: 200) Rectangle().frame(height: 200) Rectangle().frame(height: 200) Rectangle().frame(height: 200) } } .safeAreaBar(edge: .top) { Text("Test") } .navigationTitle(Title") } } }
4
1
276
14h
Bug: Xcode 26.2 wants `ENABLE_DEBUG_DYLIB`: How do I enable that in `Package.swift`?
Xcode tells me Previewing in executable targets now requires a new build layout for unoptimized builds. Either set ENABLE_DEBUG_DYLIB to YES for this target, or break out your preview code into a separate framework with its own scheme. How do enable that in Package.swift. swiftSettings don't work (.define and unsafeFlags with -D ...). Creating a library product that the executable then depends on doesn't help either. I have two targets, one is an executable target. The #Preview macro is in the non-executable target.
2
1
73
1d
SwiftUI: UNUserNotificationCenter delegate not called on cold start when opening notification
I'm sending local push notifications and want to show specific content based on the id of any notification the user opens. I'm able to do this with no issues when the app is already running in the background using the code below. final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { let container = AppContainer() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { let center = UNUserNotificationCenter.current() center.delegate = self return true } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) { container.notifications.handleResponse(response) completionHandler() } } However, the delegate never fires if the app was terminated before the user taps the notification. I'm looking for a way to fix this without switching my app lifecycle to UIKit. This is a SwiftUI lifecycle app using UIApplicationDelegateAdaptor. @main struct MyApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } } I’m aware notification responses may be delivered via launchOptions on cold start, but I’m unsure how to bridge that cleanly into a SwiftUI lifecycle app without reverting to UIKit.
0
0
17
1d
SwiftUI: AlignmentGuide in Overlay not working when in if block
Scenario A SwiftUI view has an overlay with alignment: .top, the content uses .alignmentGuide(.top) {} to adjust the placement. Issue When the content of the overlay is in an if-block, the alignment guide is not adjusted. Example code The example shows 2 views. Not working example, where the content is an if-block. Working example, where the content is not in an if-block Screenshot: https://github.com/simonnickel/FB15248296-SwiftUIAlignmentGuideInOverlayConditional/blob/main/screenshot.png Tested on - Xcode Version 16.0 RC (16A242) on iOS 18.0 Code // Not working .overlay(alignment: .top) { if true { // This line causes .alignmentGuide() to fail Text("Test") .alignmentGuide(.top, computeValue: { dimension in dimension[.bottom] }) } } // Working .overlay(alignment: .top) { Text("Test") .alignmentGuide(.top, computeValue: { dimension in dimension[.bottom] }) } Also created a Feedback: FB15248296 Example Project is here: https://github.com/simonnickel/FB15248296-SwiftUIAlignmentGuideInOverlayConditional/tree/main
1
2
428
2d
Swipe to go back still broken with Zoom navigation transition.
When you use .navigationTransition(.zoom(sourceID: "placeholder", in: placehoder)) for navigation animation, going back using the swipe gesture is still very buggy on IOS26. I know it has been mentioned in other places like here: https://developer.apple.com/forums/thread/796805?answerId=856846022#856846022 but nothing seems to have been done to fix this issue. Here is a video showing the bug comparing when the back button is used vs swipe to go back: https://imgur.com/a/JgEusRH I wish there was a way to at least disable the swipe back gesture until this bug is fixed.
4
0
272
2d
Custom @Observable RandomAcccessCollection List/ForEach issues
I'm trying to understand the behavior I'm seeing here. In the following example, I have a custom @Observable class that adopts RandomAccessCollection and am attempting to populate a List with it. If I use an inner collection property of the instance (even computed as this shows), the top view identifies additions to the list. However, if I just use the list as a collection in its own right, it detects when a change is made, but not that the change increased the length of the list. If you add text that has capital letters you'll see them get sorted correctly, but the lower list retains its prior count. The choice of a List initializer with the model versus an inner ForEach doesn't change the outcome, btw. If I cast that type as an Array(), effectively copying its contents, it works fine which leads me to believe there is some additional Array protocol conformance that I'm missing, but that would be unfortunate since I'm not sure how I would have known that. Any ideas what's going on here? The new type can be used with for-in scenarios fine and compiles great with List/ForEach, but has this issue. I'd like the type to not require extra nonsense to be used like an array here. import SwiftUI fileprivate struct _VExpObservable6: View { @Binding var model: ExpModel @State private var text: String = "" var body: some View { NavigationStack { VStack(spacing: 20) { Spacer() .frame(height: 40) HStack { TextField("Item", text: $text) .textFieldStyle(.roundedBorder) .textContentType(.none) .textCase(.none) Button("Add Item") { guard !text.isEmpty else { return } model.addItem(text) text = "" print("updated model #2 using \(Array(model.indices)):") for s in model { print("- \(s)") } } } InnerView(model: model) OuterView(model: model) } .listStyle(.plain) .padding() } } } // - displays the model data using an inner property expressed as // a collection. fileprivate struct InnerView: View { let model: ExpModel var body: some View { VStack { Text("Model Inner Collection:") .font(.title3) List { ForEach(model.sorted, id: \.self) { item in Text("- \(item)") } } .border(.darkGray) } } } // - displays the model using the model _as the collection_ fileprivate struct OuterView: View { let model: ExpModel var body: some View { VStack { Text("Model as Collection:") .font(.title3) // - the List/ForEach collections do not appear to work // by default using the @Observable model (RandomAccessCollection) // itself, unless it is cast as an Array here. List { // ForEach(Array(model), id: \.self) { item in ForEach(model, id: \.self) { item in Text("- \(item)") } } .border(.darkGray) } } } #Preview { @Previewable @State var model = ExpModel() _VExpObservable6(model: $model) } @Observable fileprivate final class ExpModel: RandomAccessCollection { typealias Element = String var startIndex: Int { 0 } var endIndex: Int { sorted.count } init() { _listData = ["apple", "yellow", "about"] } subscript(_ position: Int) -> String { sortedData()[position] } var sorted: [String] { sortedData() } func addItem(_ item: String) { _listData.append(item) _sorted = nil } private var _listData: [String] private var _sorted: [String]? private func sortedData() -> [String] { if let ret = _sorted { return ret } let ret = _listData.sorted() _sorted = ret return ret } }
2
0
156
2d
ARView ignores multi-touch events
Hi, How to enable multitouch on ARView? Touch functions (touchesBegan, touchesMoved, ...) seem to only handle one touch at a time. In order to handle multiple touches at a time with ARView, I have to either: Use SwiftUI .simultaneousGesture on top of an ARView representable Position a UIView on top of ARView to capture touches and do hit testing by passing a reference to ARView Expected behavior: ARView should capture all touches via touchesBegan/Moved/Ended/Cancelled. Here is what I tried, on iOS 26.1 and macOS 26.1: ARView Multitouch The setup below is a minimal ARView presented by SwiftUI, with touch events handled inside ARView. Multitouch doesn't work with this setup. Note that multitouch wouldn't work either if the ARView is presented with a UIViewController instead of SwiftUI. import RealityKit import SwiftUI struct ARViewMultiTouchView: View { var body: some View { ZStack { ARViewMultiTouchRepresentable() .ignoresSafeArea() } } } #Preview { ARViewMultiTouchView() } // MARK: Representable ARView struct ARViewMultiTouchRepresentable: UIViewRepresentable { func makeUIView(context: Context) -> ARView { let arView = ARViewMultiTouch(frame: .zero) let anchor = AnchorEntity() arView.scene.addAnchor(anchor) let boxWidth: Float = 0.4 let boxMaterial = SimpleMaterial(color: .red, isMetallic: false) let box = ModelEntity(mesh: .generateBox(size: boxWidth), materials: [boxMaterial]) box.name = "Box" box.components.set(CollisionComponent(shapes: [.generateBox(width: boxWidth, height: boxWidth, depth: boxWidth)])) anchor.addChild(box) return arView } func updateUIView(_ uiView: ARView, context: Context) { } } // MARK: ARView class ARViewMultiTouch: ARView { required init(frame: CGRect) { super.init(frame: frame) /// Enable multi-touch isMultipleTouchEnabled = true cameraMode = .nonAR automaticallyConfigureSession = false environment.background = .color(.gray) /// Disable gesture recognizers to not conflict with touch events /// But it doesn't fix the issue gestureRecognizers?.forEach { $0.isEnabled = false } } required dynamic init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { /// # Problem /// This should print for every new touch, up to 5 simultaneously on an iPhone (multi-touch) /// But it only fires for one touch at a time (single-touch) print("Touch began at: \(touch.location(in: self))") } } } Multitouch with an Overlay This setup works, but it doesn't seem right. There must be a solution to make ARView handle multi touch directly, right? import SwiftUI import RealityKit struct MultiTouchOverlayView: View { var body: some View { ZStack { MultiTouchOverlayRepresentable() .ignoresSafeArea() Text("Multi touch with overlay view") .font(.system(size: 24, weight: .medium)) .foregroundStyle(.white) .offset(CGSize(width: 0, height: -150)) } } } #Preview { MultiTouchOverlayView() } // MARK: Representable Container struct MultiTouchOverlayRepresentable: UIViewRepresentable { func makeUIView(context: Context) -> UIView { /// The view that SwiftUI will present let container = UIView() /// ARView let arView = ARView(frame: container.bounds) arView.autoresizingMask = [.flexibleWidth, .flexibleHeight] arView.cameraMode = .nonAR arView.automaticallyConfigureSession = false arView.environment.background = .color(.gray) let anchor = AnchorEntity() arView.scene.addAnchor(anchor) let boxWidth: Float = 0.4 let boxMaterial = SimpleMaterial(color: .red, isMetallic: false) let box = ModelEntity(mesh: .generateBox(size: boxWidth), materials: [boxMaterial]) box.name = "Box" box.components.set(CollisionComponent(shapes: [.generateBox(width: boxWidth, height: boxWidth, depth: boxWidth)])) anchor.addChild(box) /// The view that will capture touches let touchOverlay = TouchOverlayView(frame: container.bounds) touchOverlay.autoresizingMask = [.flexibleWidth, .flexibleHeight] touchOverlay.backgroundColor = .clear /// Pass an arView reference to the overlay for hit testing touchOverlay.arView = arView /// Add views to the container. /// ARView goes in first, at the bottom. container.addSubview(arView) /// TouchOverlay goes in last, on top. container.addSubview(touchOverlay) return container } func updateUIView(_ uiView: UIView, context: Context) { } } // MARK: Touch Overlay View /// A UIView to handle multi-touch on top of ARView class TouchOverlayView: UIView { weak var arView: ARView? override init(frame: CGRect) { super.init(frame: frame) isMultipleTouchEnabled = true isUserInteractionEnabled = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let totalTouches = event?.allTouches?.count ?? touches.count print("--- Touches Began --- (New: \(touches.count), Total: \(totalTouches))") for touch in touches { let location = touch.location(in: self) /// Hit testing. /// ARView and Touch View must be of the same size if let arView = arView { let entity = arView.entity(at: location) if let entity = entity { print("Touched entity: \(entity.name)") } else { print("Touched: none") } } } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { let totalTouches = event?.allTouches?.count ?? touches.count print("--- Touches Cancelled --- (Cancelled: \(touches.count), Total: \(totalTouches))") } }
2
0
403
3d
Cannot Accept CloudKit Share After First App Install
I have an iOS app (1Address) which allows users to share their address with family and friends using CloudKit Sharing. Users share their address record (CKRecord) via a share link/url which when tapped allows the receiving user to accept the share and have a persistent view into the sharing user's address record (CKShare). However, most users when they recieve a sharing link do not have the app installed yet, and so when a new receiving user taps the share link, it prompts them to download the app from the app store. After the new user downloads the app from the app store and opens the app, my understanding is that the system (iOS) will/should then vend to my app the previously tapped cloudKitShareMetadata (or share url), however, this metadata is not being vended by the system. This forces the user to re-tap the share link and leads to some users thinking the app doesn't work or not completing the sharing / onboarding flow. Is there a workaround or solve for this that doesn't require the user to tap the share link a second time? In my scene delegate I am implementing: func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {...} And also func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {...} And also: func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) {...} And: func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {...} Unfortunately, none of these are called or passed metadata on the initial app run after install. Only after the user goes back and taps a link again can they accept the share. This documentation: https://developer.apple.com/documentation/cloudkit/ckshare says that adding the CKSharingSupported key to your app's Info.plist file allows the system to launch your app when a user taps or clicks a share URL, but it does not clarify what should happen if your app is being installed for the first time. This seems to imply that the system is holding onto the share metadata and/or url, but for some reason it is not being vended to the app on first run. Open to any ideas here for how to fix and I also filed feedback: FB20934189.
2
1
67
3d
SwiftUI Instruments Template doesn't work
I am profiling a simple SwiftUI test app on my new iPhone through my new MacBook Pro and everything is version 26.2 (iOS, macOS, Xcode). I run Instruments with the SwiftUI template using all of the default settings and get absolutely zero data after interacting with the app for about 20 seconds. Using the Time Profiler template yields trace data. Trying the SwiftUI template again with the sample Landmarks app has the same issue as my app.
2
0
81
5d
SwiftData & CloudKit: Arrays of Codable Structs Causing NSKeyedUnarchiveFromData Error
I have SwiftData models containing arrays of Codable structs that worked fine before adding CloudKit capability. I believe they are the reason I started seeing errors after enabling CloudKit. Example model: @Model final class ProtocolMedication { var times: [SchedulingTime] = [] // SchedulingTime is Codable // other properties... } After enabling CloudKit, I get this error logged to the console: 'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release CloudKit Console shows this times data as "plain text" instead of "bplist" format. Other struct/enum properties display correctly (I think) as "bplist" in CloudKit Console. The local SwiftData storage handled these arrays fine - this issue only appeared with CloudKit integration. What's the recommended approach for storing arrays of Codable structs in SwiftData models that sync with CloudKit?
8
1
678
6d
SwiftUI .task does not update its references on view update
I have this sample code import SwiftUI struct ContentView: View { var body: some View { ParentView() } } struct ParentView: View { @State var id = 0 var body: some View { VStack { Button { id+=1 } label: { Text("update id by 1") } TestView(id: id) } } } struct TestView: View { var sequence = DoubleGenerator() let id: Int var body: some View { VStack { Button { sequence.next() } label: { Text("print next number").background(content: { Color.green }) } Text("current id is \(id)") }.task { for await number in sequence.stream { print("next number is \(number)") } } } } final class DoubleGenerator { private var current = 1 private let continuation: AsyncStream<Int>.Continuation let stream: AsyncStream<Int> init() { var cont: AsyncStream<Int>.Continuation! self.stream = AsyncStream { cont = $0 } self.continuation = cont } func next() { guard current >= 0 else { continuation.finish() return } continuation.yield(current) current &*= 2 } } the print statement is only ever executed if I don't click on the update id by 1 button. If i click on that button, and then hit the print next number button, the print statement doesn't print in the xcode console. I'm thinking it is because the change in id triggered the view's init function to be called, resetting the sequence property and so subsequent clicks to the print next number button is triggering the new version of sequence but the task is still referring its previous version. Is this expected behaviour? Why in onChange and Button, the reference to the properties is always up to date but in .task it is not?
1
0
153
6d
NSHostingView stops receiving mouse events when layered above another NSHostingView (macOS Tahoe 26.2)
I’m running into a problem with SwiftUI/AppKit event handling on macOS Tahoe 26.2. I have a layered view setup: Bottom: AppKit NSView (NSViewRepresentable) Middle: SwiftUI view in an NSHostingView with drag/tap gestures Top: Another SwiftUI view in an NSHostingView On macOS 26.2, the middle NSHostingView no longer receives mouse or drag events when the top NSHostingView is present. Events pass through to the AppKit view below. Removing the top layer immediately restores interaction. Everything works correctly on macOS Sequoia. I’ve posted a full reproducible example and detailed explanation on Stack Overflow, including a single-file demo: Stack Overflow post: https://stackoverflow.com/q/79862332 I also found a related older discussion here, but couldn’t get the suggested workaround to apply: https://developer.apple.com/forums/thread/759081 Any guidance would be appreciated. Thanks!
4
0
322
6d
Animation does not work with List, while works with ScrollView + ForEach
Why there is a working animation with ScrollView + ForEach of items removal, but there is none with List? ScrollView + ForEach: struct ContentView: View { @State var items: [String] = Array(1...5).map(\.description) var body: some View { ScrollView(.vertical) { ForEach(items, id: \.self) { item in Text(String(item)) .frame(maxWidth: .infinity, minHeight: 50) .background(.gray) .onTapGesture { withAnimation(.linear(duration: 0.1)) { items = items.filter { $0 != item } } } } } } } List: struct ContentView: View { @State var items: [String] = Array(1...5).map(\.description) var body: some View { List(items, id: \.self) { item in Text(String(item)) .frame(maxWidth: .infinity, minHeight: 50) .background(.gray) .onTapGesture { withAnimation(.linear(duration: 0.1)) { items = items.filter { $0 != item } } } } } }```
5
0
121
1w
SwiftUI menu not resizing images
I failed to resize the icon image from instances of NSRunningApplication. I can only get 32×32 while I'm expecting 16×16. I felt it unintuitive in first minutes… Then I figured out that macOS menu seems not allowing many UI customizations (for stability?), especially in SwiftUI. What would be my best solution in SwiftUI? Must I write some boilerplate SwiftUI-AppKit bridging?
1
0
71
1w
WWDC21 Demystify SwiftUI question
When the guy was talking about structural identity, starting at about 8:53, he mentioned how the swiftui needs to guarantee that the two views can't swap places, and it does this by looking at the views type structure. It guarantees that the true view will always be an A, and the false view will always be a B. Not sure exactly what he means because views can't "swap places" like dogs. Why isn't just knowing that some View is shown in true, and another is shown in false, enough for its identity? e.g. The identity could be "The view on true" vs "The view on false", same as his example with "The dog on the left" vs "The dog on the right"
0
0
49
1w