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

Exporting and restoring AttributedString in rich TextEditor (iOS 26)
I am working with the rich TextEditor introduced in iOS 26, but I am having trouble preserving AttributedString formatting when converting to/from RTF. Here is my exporting logic in my view model (AttributedString to RTF) let nsAttrStr = NSAttributedString(self.text) // text is an AttributedString (bound to the TextEditor input) let range = NSRange(location: 0, length: nsAttrStr.length) let options: [NSAttributedString.DocumentAttributeKey: Any] = [ .documentType: NSAttributedString.DocumentType.rtf ] guard let data = try? nsAttrStr.data(from: range, documentAttributes: options) else { return nil } let rtfBase64 = data.base64EncodedString() When I inspect the result, it seems to lose the font, size, boldness, etc which is being correctly rendered in the TextEditor. When I convert back from RTF to an AttributedString, it reverts to the default text formatting applied in the TextEditor. Any ideas what could be going wrong?
1
0
164
Oct ’25
SwiftUI document based app: weird NavBar colors since iOS 26
I have multiple document based SwiftUI apps without any NavigationBar customization. Since upgrading to iOS 26 , when these apps launch, sometimes their navigation bar icons appear grey (as if only the button shadows were showing) and the document title is white, so it’s invisible. One of the apps has an Inspector: here, whenever the Inspector appears, the colors are correct. This behavior has been consistent since the first iOS 26 developer beta and can be reproduced on iOS 26.1 beta 23B5064e. So far I have only managed to reproduce this in light mode.
1
1
129
Oct ’25
View.navigationLinkIndicatorVisibility(_:) crashes apps running on iOS 18.x
Apps crash on launch when using View.navigationLinkIndicatorVisibility(_:) (which is iOS 17.0+ iPadOS 17.0+ Mac Catalyst 17.0+). Catalyst also crashes. Stack trace starts with: Symbol not found: _$s7SwiftUI17EnvironmentValuesV33_navigationIndicatorVisibilityABIAA0G0OvpMV Xcode 26.0.1 (17A400) iPadOS 18.3.1 (22D8075) It also crashed a user on iOS 18.6.2 macOS 15.6.1 (24G90) FB20596543 import SwiftUI @main struct NavLinkDisabledApp: App { var body: some Scene { WindowGroup { NavigationStack { List { NavigationLink("Text") {} .navigationLinkIndicatorVisibility(.hidden) } } } } }
4
0
132
Oct ’25
[iOS 26] iOS App Does Not Receive Deep Link from Widget When Using widgetAccentedRenderingMode on Image
Summary When a SwiftUI widget uses a Link containing an Image modified with .widgetAccentedRenderingMode (using any mode except .fullColor), tapping the image on the widget launches the app but does not pass the expected deep link URL to the SceneDelegate. Steps to Reproduce Create a SwiftUI Widget View with a Link: struct ImageView: View { var image: UIImage var body: some View { Link(URL(string: "myapp://image")!) { Image(uiImage: image) .resizable() .widgetAccentedRenderingMode(.accentedDesaturated) // or any mode other than .fullColor .scaledToFill() .clipped() } } } Add Custom URL Scheme in Info.plist: <dict> <key>CFBundleURLName</key> <string>com.company.myapp</string> <key>CFBundleURLSchemes</key> <array> <string>myapp</string> </array> </dict> Implement Deep Link Handling in SceneDelegate: func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if let url = connectionOptions.urlContexts.first?.url { handle(url) } } func scene(_ scene: UIScene, openURLContexts urlContexts: Set<UIOpenURLContext>) { if let url = urlContexts.first?.url { handle(url) } } private func handle(_ url: URL) { // Process URL here } Run the application on a device or simulator. Add the widget to the Home Screen. Tap the image inside the widget. Expected Result The application launches and receives the URL in SceneDelegate, as expected. Actual Result The application launches, but the URL is not passed to SceneDelegate. Both connectionOptions.urlContexts and openURLContexts are empty.
2
1
299
Oct ’25
Bottom toolbar Button truncated on Mac Catalyst 26
On Mac Catalyst 26, a Button bar item in a bottom toolbar look squished. This happens only when the "Mac Catalyst Interface" option is set to "Optimize for Mac". When it is set to "Scale to match iPad", the buttons look fine. For example, in the screenshots below, the text button should say "Press Me", instead of "…" A simple reproducible snippet and a screenshot below. The toolbar button comparison between "Scale to match iPad" and "Optimize for Mac" are shown. Optimize for Mac Scale to match iPad import SwiftUI struct ContentView: View { @State private var selectedItem: String? = "Item 1" let items = ["Item 1", "Item 2"] var body: some View { NavigationSplitView { List(items, id: \.self, selection: $selectedItem) { item in Text(item) } .navigationTitle("Items") } detail: { if let selectedItem = selectedItem { Text("Detail view for \(selectedItem)") .toolbar { ToolbarItemGroup(placement: .bottomBar) { Text("Hello world") Spacer() Button("Press Me") { } Spacer() Button { } label: { Image(systemName: "plus") .imageScale(.large) } } } } else { Text("Select an item") } } } }
0
1
170
Oct ’25
iOS 26 AttributedString TextEditor bold and italic
Is there a way to constrain the AttributedTextFormattingDefinition of a TextEditor to only bold/italic/underline/strikethrough, without showing the full Font UI? struct CustomFormattingDefinition: AttributedTextFormattingDefinition { struct Scope: AttributeScope { let font: AttributeScopes.SwiftUIAttributes.FontAttribute let underlineStyle: AttributeScopes.SwiftUIAttributes.UnderlineStyleAttribute let strikethroughStyle: AttributeScopes.SwiftUIAttributes.StrikethroughStyleAttribute } var body: some AttributedTextFormattingDefinition<Scope> { ValueConstraint(for: \.font, values: [MyStyle.defaultFont, MyStyle.boldFont, MyStyle.italicFont, MyStyle.boldItalicFont], default: MyStyle.defaultFont) ValueConstraint(for: \.underlineStyle, values: [nil, .single], default: .single) ValueConstraint(for: \.strikethroughStyle, values: [nil, .single], default: .single) } } If I remove the Font attribute from the scope, the Bold and Italic buttons disappear. And if the Font attribute is defined, even if it's restricted to one typeface in 4 different styles, the full typography UI is displayed.
1
0
86
Oct ’25
Confirmation dialog in NavigationStack toolbar button appears inconsistently or in wrong position
Hello, I’m encountering an issue with a confirmation dialog presented from a toolbar button within a NavigationStack. The dialog rarely appears, and when it does, it sometimes shows up in unexpected positions on the screen. The view is presented in a sheet. Environment: • Xcode 26.0.1 • iOS 26.0 (iPhone 17 Pro Simulator) Has anyone else experienced this behavior or found a reliable workaround? Here is the video of the issue: Video And the warning that occurs when I press the button: Dismissing a zoom transition to a view not in the view hierarchy will trigger a fallback transition. To correct the error, be sure to a provide a view that's visible and in a window. View: <_UINavigationBarPlatterGlassView: 0x1200e46d0> → <_UINavigationBarPlatterContentView: 0x1200e4510> → <_UINavigationBarPlatterAnimationView: 0x1200e4360> → <_UINavigationBarPlatterAnimationView: 0x1200e41b0> → <_UINavigationBarPlatterAnimationView: 0x1200e4000> → <_UINavigationBarPlatterAnimationView: 0x1200951f0> → <_UINavigationBarPlatterView: 0x1200e3d20> → <UIKit.NavigationBarPlatterContainer: 0x12028c850> → <UIKit.NavigationBarTransitionContainer: 0x12029c8b0> → <UIKit.NavigationBarContentView: 0x106b91400> → <SwiftUI.UIKitNavigationBar: 0x12029c600> → <UILayoutContainerView: 0x1202c05d0; name=UILayoutContainerView (SwiftUI.UIKitNavigationController)>
1
0
108
Oct ’25
When is the StateObject’s autoclosure actually called?
The signature of the StateObject initializer is init(wrappedValue thunk: @autoclosure @escaping () -> ObjectType). The fact that the autoclosure is marked as escaping intrigues me, because that suggests that it could be called after the init has returned. Why this is interesting is because I have some code where the viewmodel given to the @StateObject depends on an implicitly unwrapped optional type, and I expect the top level initialization of the StateObject to crash because the implicitly unwrapped optional is not ready yet, but to my surprise it did not. My theory is that the autoclosure is being called after the View’s initialization had been called, when the dependency is ready. heres a minimal sample of that. class MyDependency: ObservableObject { @Published var value = "Hello" } class MyViewModel: ObservableObject { let dependency: MyDependency init(dependency: MyDependency = TestApp.dependency) { self.dependency = dependency print("✅ ViewModel initialized with dependency:", dependency.value) } } struct ContentView: View { @StateObject private var viewModel = MyViewModel() // ⚠️ expected crash? var body: some View { Text(viewModel.dependency.value).onAppear { TestApp.dependency = Dependency()// dependency is set here after init has been called } } } @main struct TestApp: App { static var dependency: MyDependency! // not ready yet var body: some Scene { WindowGroup { ContentView() } }```
0
0
122
Oct ’25
NavigationSplitView: Make button clickable in detail-section safe area
Hi, I've tried to find a solution for this problem for weeks now but it seems no one knows how to solve it and Apple doesn't seem to care. I have a NavigationSplitView with two columns. In the detail column I have a button - or any other clickable control - which is placed in the very top where usually the safe area resides. The button is NOT clickable when he is in the safe area and I have NO idea why. I know I can place buttons in safe areas of other views and they are clickable. Please have a look at the code: `struct NavTestView: View { var body: some View { GeometryReader { p in VStack(spacing: 0) { NavigationSplitView { List(names) { Text($0.name).frame(width: p.size.width) .background(Color.green) }.listRowSpacing(p.size.height * 0.15 / 100 ) .toolbar(.hidden, for: .navigationBar) } detail: { TestView().ignoresSafeArea() }.frame(width: p.size.width, height: p.size.height, alignment: .topLeading) .background(Color.yellow) } } } } struct TestView: View { var body: some View { GeometryReader { p in let plusButton = IconButton(imageName: "plus.circle.fill", color: Color(uiColor: ThemeColor.SeaFoam.color), imageWidth: p.size.width * 5 / 100, buttonWidth: p.size.width * 5 / 100) let regularAddButton = Button(action: { log.info("| Regular Add Button pressed") } ) { plusButton } VStack { regularAddButton }.frame(width: p.size.width , height: p.size.height, alignment: .top) .background(Color.yellow) } } } ` this code produces the following screen: Any help would be really greatly appreciated! Thank you! Frank
1
0
671
Oct ’25
SwiftUI buttons behind NSToolbarView are not clickable on macOS 26 beta
Overview Starting with macOS 26 beta 1, a new NSGlassContainerView is added inside NSToolbarView. This view intercepts mouse events, so any SwiftUI Button (or other interactive view) overlaid on the title‑bar / toolbar area no longer receives clicks. (The same code works fine on macOS 15 and earlier.) Filed as FB18201935 via Feedback Assistant. Reproduction (minimal project) macOS 15 or earlier → button is clickable macOS 26 beta → button cannot be clicked (no highlight, no action call) @main struct Test_macOS26App: App { init() { // Uncomment to work around the issue (see next section) // enableToolbarClickThrough() } var body: some Scene { WindowGroup { ContentView() } .windowStyle(.hiddenTitleBar) // ⭐️ hide the title bar } } struct ContentView: View { var body: some View { NavigationSplitView { List { Text("sidebar") } } detail: { HSplitView { listWithOverlay listWithOverlay } } } private var listWithOverlay: some View { List(0..<30) { Text("item: \($0)") } .overlay(alignment: .topTrailing) { // ⭐️ overlay in the toolbar area Button("test") { print("test") } .glassEffect() .ignoresSafeArea() } } } Investigation In Xcode View Hierarchy Debugger, a layer chain NSToolbarView > NSGlassContainerView sits in front of the button. -[NSView hitTest:] on NSGlassContainerView returns itself, so the event never reaches the SwiftUI layer. Swizzling hitTest: to return nil when the result is the view itself makes the click go through: func enableToolbarClickThrough() { guard let cls = NSClassFromString("NSGlassContainerView"), let m = class_getInstanceMethod(cls, #selector(NSView.hitTest(_:))) else { return } typealias Fn = @convention(c)(AnyObject, Selector, NSPoint) -> Unmanaged<NSView>? let origIMP = unsafeBitCast(method_getImplementation(m), to: Fn.self) let block: @convention(block)(AnyObject, NSPoint) -> NSView? = { obj, pt in guard let v = origIMP(obj, #selector(NSView.hitTest(_:)), pt)?.takeUnretainedValue() else { return nil } return v === (obj as AnyObject) ? nil : v // ★ make the container transparent } method_setImplementation(m, imp_implementationWithBlock(block)) } Questions / Call for Feedback Is this an intentional behavioral change? If so, what is the recommended public API or pattern for allowing clicks to reach views overlaid behind the toolbar? Any additional data points or confirmations are welcome—please reply if you can reproduce the issue or know of an official workaround. Thanks in advance!
3
0
249
Oct ’25
NavigationSplitView detail view with safearea
Hi, I have a NavigationSplitView with a view in the detail section: NavigationSplitView { ZStack { Color.black.ignoresSafeArea() gradientBlack2Blue.opacity(0.25) .ignoresSafeArea() GeometryReader { p in VStack { List { SidebarViewCell(id: "1", text: "Steuersätze" , type: .TAX_MASTERDATA , selectedMasterdataType: $selectedMasterdataType) }.listRowSpacing(size.height * 1.25 / 100 ) .scrollContentBackground(.hidden) .toolbar(.hidden, for: .navigationBar) .frame(width: p.size.width * 98 / 100 , height: p.size.height, alignment: .topLeading). }alignment: .topLeading) } } } detail: { MasterdataDetailView().ignoresSafeArea() } }.navigationSplitViewStyle(.balanced) When I place a Button-Control in the MasterdataDetailView it cannot be clicked because it is in the safe area. How can I make it clickable? Best Regards, Frank
8
0
1.6k
Oct ’25
Correct way to handle 2 to 3 column switch
I'm using a NavigationSplitView on macOS which needs to show 2 or 3 columns depending on the selection of the sidebar. Column 1 has a list of main activities. Some of these just have some data to show and some have a sublist. Currently, when an item that has no sublist is selected, I set the 2nd column (content:) to: Spacer() .navigationSplitViewColumnWidth(0) This works, although it started hitting bugs requiring a workaround on macOS 26, which got me wondering, what is the correct approach here? NavigationSplitViewVisibility.doubleColumn is not the solution, as this hides column 1, not column 2.
Topic: Design SubTopic: General Tags:
0
0
792
Oct ’25
Simply including "@Environment(\.dismiss) ..." causes multiple calls to a view's body
When I run the code below, the trace, "Called", is shown 3-4 times initially. If I click on a color row, the trace shows 9 times. Why is that? If I comment out the line, @Environment(\.dismiss) private var dismiss, the trace shows only 1 time, as expected. I've read a number of reports regarding dismiss() which seems to be very brittle. It often causes an infinite loop. But I need to dismiss a view. Its older counterpart, @Environment(\.presentationMode), seems to cause infinite loop at times. Are there other ways to dismiss a view without suffering these issues? struct TestNavigationLink: View { @Environment(\.dismiss) private var dismiss var body: some View { let _ = print("Called") NavigationStack { List { NavigationLink("Mint") { ColorDetail(color: .mint) } } .navigationTitle("Colors") } } // body struct ColorDetail: View { var color: Color var body: some View { color.navigationTitle(color.description) } } }
2
1
683
Oct ’25
I found a liquid glass bug
When I use rotation3DEffect to rorate a UI element with liquid glass, the liquid glass turns black and expands struct TestCardView: View { @State var rotation:CGFloat = 0.0 @State var vertical: Double = 0 @State var horizontal: Double = 0 var body: some View { ZStack { Image("paintImage") .resizable() .scaledToFill() .ignoresSafeArea() .blur(radius: 10) // Card container ZStack { // Add content here Image("paintImage") .resizable() .clipShape(RoundedRectangle(cornerRadius: 20)) .padding(10) VStack { Spacer() Text("Placeholder text Placeholder text Placeholder text Placeholder text ") .multilineTextAlignment(.center) .padding(12) .glassEffect(.clear, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) .shadow(color: .black.opacity(0.2), radius: 8, x: 0, y: 4) .padding(.bottom, 8) } .padding(25) } .frame(width: 360, height: 600) .clipShape(RoundedRectangle(cornerRadius: 20)) .glassEffect(.clear, in: RoundedRectangle(cornerRadius: 20)) .rotation3DEffect(.degrees(vertical),axis: (x: 1, y: 0, z: 0)) .rotation3DEffect(.degrees(horizontal),axis: (x: 0, y: 1, z: 0)) .gesture( DragGesture(minimumDistance: 0) .onChanged { value in withAnimation{ vertical = min(max(Double(value.translation.height / 10), -20), 20) horizontal = min(max(Double(value.translation.width / 10), -15), 15) } } .onEnded { _ in withAnimation(.easeOut(duration: 0.5)) { vertical = 0 horizontal = 0 } } ) } } }
2
0
95
Oct ’25
NavigationPath.append but .navigationDestination Not Being Called
I am trying to do a bit of fancy navigation in SwiftUI using NavigationPath and am having a problem. I have a root view with includes a button: struct ClassListScreen: View { @Bindable private var router = AppRouter.shared @State private var addCourse: Bool = false ... var body: some View { ... Button("Add Class") { router.currentPath.append(addCourse) }.buttonStyle(.borderedProminent) ... .navigationDestination(for: Bool.self){ _ in ClassAddDialog { course in sortCourses() } } } } router.currentPath is the NavigationPath associated with the operative NavigationStack. (This app has a TabView and each Tab has its own NavigationStack and NavigationPath). Tapping the button correctly opens the ClassAddDialog. In ClassAddDialog is another button: struct ClassAddDialog: View { @Bindable private var router = AppRouter.shared @State private var idString: String = "" ... var body: some View { ... Button("Save") { let course = ... ... (save logic) idString = course.id.uuidString var path = router.currentPath path.removeLast() path.append(idString) router.currentPath = path }.buttonStyle(.borderedProminent) ... .navigationDestination(for: String.self) { str in if let id = UUID(uuidString: str), let course = Course.findByID(id, with: context) { ClassDetailScreen(course: course) } } } } My intent here is that tapping the Save button in ClassAddDialog would pop that view and move directly to the ClassDetailScreen (without returning to the root ClassListScreen). The problem is that the code inside the navigationDestination is NEVER hit. (I.e., a breakpoint on the if let ... statement) never fires. I just end up on a (nearly) blank view with a warning triangle icon in its center. (And yes, the back button takes me to the root, so the ClassAddDialog WAS removed as expected.) And I don't understand why. Can anyone share any insight here?
0
1
76
Oct ’25
Is ContactAccessButton broken?
Simple question - on iOS 26 ContactAccessButton does not appear to show any UI when attempting to search for a contact in either the contact access picker on the ContactAccessButton. This behavior occurs in the Apple provided sample code , as well as a basic example: struct ContentView: View { @State var searchText : String = "" var body: some View { VStack { TextField("Search", text: $searchText) ContactAccessButton( queryString: searchText, ignoredEmails: nil, ignoredPhoneNumbers: nil, approvalCallback: { identifiers in print(identifiers) }) } .padding() } } Am I doing something wrong or is this just not working?
1
0
83
Oct ’25
Scroll TextEditor to cursor position
Hello. Is there a good SwiftUI approach on getting the TextEditor cursor position? I have a TextEditor and sometimes when we have a longer text inside it, the cursor is not seen because the keyboard is above covering the bottom of the TextEditor. I would like to somehow detect the position of the cursor, and if it's on the last line of the TextEditor, scroll to the bottom. I've already checked a bit and didn't find any good method of doing this in SwiftUI. If you have any ideas on how to do this, or even a different method any help would be highly appreciated. Thank you!
1
3
807
Oct ’25
"The compiler is unable to type-check this expression..."
"/Users/rich/Work/IdeaBlitz/IdeaBlitz/IdeaListView.swift:30:25 The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" Is it just me? I get this on syntax errors, missing commas, missing quotes, and for no particular reason at all that I can see. I don't think I've been able to write a single, simple, SwiftUI view without seeing this multiple times. "Breaking it up" just makes it harder to read. Simple, inline, 2-page views become 8-page, totally unreadable, monstrosities. Am I doing something wrong? Or is this just the state of SwiftUI today? Or is there some way to tell the compiler to take more time on this expression? I mean, if these can be broken up automatically, then why doesn't the compiler to that already?
3
0
275
Oct ’25