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 update TabViewBottomAccessoryPlacement
Playing around with the new TabViewBottomAccessoryPlacement API, but can't figure out how to update the value returned by @Environment(\.tabViewBottomAccessoryPlacement) var placement. I want to change this value programmatically, want it to be set to nil or .none on app start until user performs a specific action. (taps play on an item which creates an AVPlayer instance). Documentation I could find: https://developer.apple.com/documentation/SwiftUI/TabViewBottomAccessoryPlacement
4
3
274
2w
preferredImageDynamicRange is not marked as being available only for iOS 17 and above.
open var isAnimating: Bool { get } /// The preferred treatment to use for HDR images. By default the image view will defer to the value from its traitCollection. open var preferredImageDynamicRange: UIImage.DynamicRange /// The resolved treatment to use for HDR images. open var imageDynamicRange: UIImage.DynamicRange { get } This attribute is not marked as being applicable only in iOS 17+ versions. When viewing the UIImageView code in Xcode, the @available(iOS 17.0, *) annotation was not added, which resulted in successful compilation but caused a crash on iOS 16 devices.
3
0
80
2w
How to detect modifier keys with hardware keyboard in SwiftUI (iOS)?
Hi everyone, In UIKit, I can detect which key and modifier keys are pressed from an external hardware keyboard using the pressesBegan method in a UIResponder: override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { for press in presses { if let key = press.key { print("Key: \(key.charactersIgnoringModifiers ?? "")") print("Modifiers: \(key.modifierFlags)") } } } I am now working in SwiftUI (iOS), and I couldn’t find a direct equivalent for pressesBegan. What is the recommended way in SwiftUI to detect modifier keys + key presses from an external keyboard? Is there a built-in API, or should I always wrap a UIKit view/controller for this purpose? Thanks in advance!
0
0
32
2w
Liquid Glass / iOS 26 Tab bar positions incorrectly on iPad; repositions correctly when re-opening app
I have a TabView (no modifiers) as the top-level view in my app. Starting with iOS 26 it starts off partially "under" the Status Bar, and then repositions if I switch between apps. Starting Point After Switching To/From Another App In the simulator, pressing "Home" and then reopening the app will fix it. Anyone else seeing something similar? Is there a modifier I'm missing on TabView that might prevent this behaviour? Thanks!
4
1
280
2w
Core Data + CKSyncEngine with Swift 6 — concurrency, Sendable, and best practices validation
Hi everyone, I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6. After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using. The good news: 👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly. 👉 The demo project compiles and runs cleanly with Swift 6. However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts. Architecture Overview Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine. Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods. SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records. ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories. UI: Simple SwiftUI views bound to the ViewModels. Entities: UserEntity → represents swimmers. SwimTimeEntity → times linked to a user (1-to-many). Current Status The project works and syncs across devices. But there are two open concerns I’d like validated: Concurrency & Memory Safety Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)? Could there still be hidden risks of race conditions or memory crashes that I’m not catching? Swift 6 Sendable Compliance Currently, I still need @unchecked Sendable in the SyncEngine and repository layers. What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules? Request Please review this sample project and confirm whether the concurrency model is correct. Suggest how I can remove the @unchecked Sendable annotations safely. Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource. I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely. Environment iOS 18.5 Xcode 16.4 macOS 15.6 Swift 6 Sample Project Here is the full sample project on GitHub: 👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6] Thanks a lot for your time and for any insights! Best regards, Javier Arnáez de Pedro
3
0
391
2w
macOS 26 toolbar has wrong tint color sometimes in Dark Appearance
I have a SwiftUI Mac Catalyst app. I create a toolbar like this NavigationSplitView(columnVisibility: $sceneModel.columnVisibility, preferredCompactColumn: $preferredColumn) { sidebarView() } detail: { contentView() .toolbar { ToolbarItemGroup(placement: .topBarTrailing) { HStack { Button { sceneModel.onMaps(sender: self) } label: { Image(systemName: "map") .font(.title2) } Button { sceneModel.onSearch(sender: self) } label: { Image(systemName: "magnifyingglass") .font(.title2) } ... } } } } When my Mac Appearance is set to dark mode and the content under the toolbar is dark the toolbar looks good like this. But then if I have light content under the toolbar, the glass effect changes to light, but the tint on the icons stays white instead of changing to black and it is hard to see the icon. It looks like this. When I set the Appearance on my Mac to light, then the toolbar works just fine on both dark and light colored backgrounds. Does anyone know how I can fix this when the appearance is Dark?
8
0
153
2w
Avoid using a segmented control in a toolbar
Hi, in the Human Interface Guidelines, Apple writes: Avoid using a segmented control in a toolbar. Toolbar items act on the current screen — they don’t let people switch contexts like segmented controls do. Along with this image: Source I'm confused by this example. The screenshot seems to be showing a segmented control in a toolbar. Is this saying that the Phone app's All/Missed toggle is different from a segmented control? Under iOS 26 it seems to take a different style compared to a regular segmented control. If so, which component is used to create this filter? Could you please clarify the guidelines? Thank you.
1
0
334
2w
How To Position Controls With SwiftUI
I am coming from C#, where Forms and Controls are placed similar to Swift Storyboards. I have been trying to learn Storyboards, but keep running across tutorials regarding SwiftUI, and Storyboard examples are few. So the question becomes, "how do I position controls on a Form using SwiftUI?" See the example below. I have run across many videos that use either horizontal or vertical positioning of controls, but these examples are usually very simple, with items occupying only the center portion of the screen. I get stuck on examples that are more complicated. The example below only shows the controls for the upper part of a Form, with some type of textbox (Viewform) below making up the rest of the Form. How does one make more complicated placement of controls with SwiftUI?
10
0
346
2w
Header Blur Effect on visionOS SwiftUI
Hi, I'm looking to build something similar to the header blur in the App Store and Apple TV app settings. Does anyone know the best way to achieve this so that when there is nothing behind the header it looks the same as the rest of the view background but when content goes underneath it has a blur effect. I've seen .scrollEdgeEffect on IOS26 is there something similar for visionOS? Thanks!
0
0
97
2w
MenuBarExtra with .window style: .onHover modifier doesn't work on macOS 26 Tahoe
List { Text("ITEM 1") .onHover(perform: { hovering in debugPrint("hovering: ", hovering) }) .help("ITEM 1") Text("ITEM 2") .onHover(perform: { hovering in debugPrint("hovering: ", hovering) }) .help("ITEM 2") Text("ITEM 3") .onHover(perform: { hovering in debugPrint("hovering: ", hovering) }) .help("ITEM 3") } .fixedSize(horizontal: false, vertical: true) .frame(maxHeight: 200) } Hello everyone!!! Considering the snippet above, seems like the onHover action, including help modifiers, doesn't work for the elements of a List, on macOS Tahoe. The situation changes using a ScrollView embedding a LazyVStack, or disabling Liquid Glass from the info plist, so my guess is that the new Liquid Glass style has something to do with this issue though I didn't find any clue about it. Does anyone have any idea? Maybe there's a layer above that doesn't allow to trigger the onHover modifier? Thanks in advance for your help!
0
0
116
2w
iOS 26 @FocusState Doesn't Work If TextField Is In Toolbar
When I add a TextField with @FocusState to a toolbar, I noticed that setting focus = false doesn't cause the form to lose focus If I move the TextField out of the toolbar setting focus = false works fine. How can I unfocus the text field when the cancel button is tapped? Minimal example tested on Xcode Version 26.0 beta 6 (17A5305f): import SwiftUI struct ContentView: View { @State private var text: String = "" @FocusState private var focus: Bool var body: some View { NavigationStack { List { Text("Test List") } .toolbar { ToolbarItem(placement: .bottomBar) { TextField("Test", text: $text) .padding(.horizontal) .focused($focus) } ToolbarItem(placement: .bottomBar) { Button(role: .cancel) { focus = false // THIS DOESN'T WORK! } } } } } } #Preview { ContentView() }```
1
2
234
2w
`onTapGesture` not triggered on `Map` views
When building with iOS 26 SDK beta 5 (23A5308f), onTapGesture is no longer being triggered on Map views. This appears to be a regression in beta 5 specifically, as this issue was not present in beta 4. How to reproduce Code The following code demonstrates the issue, as seen in the videos below. import MapKit import SwiftUI struct ContentView: View { @State private var location = CGPoint.zero var body: some View { Map() .onTapGesture { location in self.location = location } .safeAreaInset(edge: .bottom) { VStack(alignment: .center) { Text("iOS \(UIDevice.current.systemVersion)") .font(.largeTitle) Text("Tapped Location") Text("\(location.x), \(location.y)") } .frame(maxWidth: .infinity, alignment: .center) .background(.background) } } } Demo The gifs below show the behavior in iOS 18.5 (in which the tap gestures are recognized and tapped coordinate is displayed in the safe area inset) and iOS 26 beta 5 (in which the tap gestures have no effect): iOS 18 iOS 26 Next steps? Is there a recommended workaround for this issue?
19
5
854
2w
Custom font ok on iOS, fuzzy on OSX
Hi! I am adding MacOS to a SwiftUI based multiplatform app in XCode, and have noticed an effect on the OTF font I am using. When started for a MacOSX target, the font looks a bit fuzzy, or too bold for the same display: Above is the display running in an iPhone 13 mini simulator, below the macOS version running for the "My Mac" target. The font is in both cases just fetched with static let tkDisplayFont = Font.custom("Segment7Standard", size: 38) Same applies in dark mode: This makes the numbers and especially the decimal point a bit harder to read. The same happens with the system font, but it is not such a problem there: I guess this is handled a bit differently between UIFont and NSFont underneath. Is there a way to tell the font to behave the same way as on iOS?
0
0
74
2w
A focused searchable modifier breaks programmatic back navigation
Calls to NavigationPath.removeLast(_:) will successfully remove items from the path, but the navigation stack UI fails to correctly update if a view in an intermediate path item had a focused searchable modifier. In this first video, the searchable modifier is unused. I can navigate to the list, make a selection and return home: In this second example, the searchable modifier is focused and a selection from the list is made. In the final screen, if I attempt to return home we can see that the navigation path size decreases but the view does not change. If the button is pressed again, we attempt to remove path items that no longer exist, causing a fatal error. Minimal Reproducible Code: import SwiftUI @main struct NavigationStackRemoveLastNBugApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State private var navigationPath = NavigationPath() var body: some View { NavigationStack(path: $navigationPath) { List { Button("List") { navigationPath.append(NavigationDestination.listView) } } .navigationDestination(for: NavigationDestination.self) { destination in switch destination { case let .selectionView(int): SelectionView(selectedNumber: int) case .listView: ListView() } } .navigationTitle("Home") } .environment(\.navigationPath, $navigationPath) } } enum NavigationDestination: Hashable { case listView case selectionView(Int) } struct ListView: View { @Environment(\.navigationPath) var navigationPath @State private var query = "" var body: some View { List(1..<5, id: \.self) { int in Button { navigationPath?.wrappedValue.append(NavigationDestination.selectionView(int)) } label: { Text(int, format: .number) } } .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always)) } } struct SelectionView: View { @Environment(\.navigationPath) var navigationPath let selectedNumber: Int @State private var pathSize: Int? var body: some View { List { LabeledContent("Selection", value: selectedNumber.formatted()) if let pathSize { LabeledContent("Navigation Path Size", value: pathSize.formatted()) } Button("Back Home") { navigationPath?.wrappedValue.removeLast(2) pathSize = navigationPath?.wrappedValue.count } } .task { pathSize = navigationPath?.wrappedValue.count } } } extension EnvironmentValues { @Entry var navigationPath: Binding<NavigationPath>? } #Preview { ContentView() } FB20395585
0
0
68
2w
What is SwiftUI API equivalent to NSSplitViewItemAccessoryViewController in macOS?
On macOS Tahoe 26, NSSplitViewController introduced the NSSplitViewItemAccessoryViewController and related-APIs in NSSplitViewController, such as addBottomAlignedAccessoryViewController(_:). Those APIs allow you to place accessory views at the top and bottom of a split view with a nice edge effect. I understand how to use them with AppKit. However, I’m not sure how to achieve the same functionality with SwiftUI.
1
0
90
2w
iOS 26 & Xcode 26 - bug with keyboard by WebView
Environment iOS 26 (23A343) Xcode 26 Reproduces on device and Simulator Description When presenting a SwiftUI WebView (native iOS 26 component) or a WKWebView/UIWebView via UIViewRepresentable, focusing a text field inside the web view and then dismissing it breaks the keyboard layout behavior. After returning to the main app, tapping any TextField causes the keyboard to cover bottom controls (e.g. buttons). Expected safe area insets are not applied. The issue is only resolved after closing and reopening the keyboard once. Steps to Reproduce Open a SwiftUI screen with WebView (via .sheet or NavigationLink). Inside the web view, tap a text field to show the keyboard. Dismiss the web view. Tap a TextField in the main app. Expected Result Layout should adjust correctly. Bottom controls stay visible above the keyboard. Actual Result Keyboard covers bottom controls. Insets are ignored until the keyboard is dismissed and reopened. Notes Reproduces with: Native SwiftUI WebView (iOS 26) WKWebView and UIWebView via UIViewRepresentable Presentation style (.sheet or navigation push) does not matter. Example video: https://youtu.be/Epgoz1vETKU FB: FB20386257 Sample Code import SwiftUI import WebKit struct ContentView: View { @State var url: URL? @FocusState private var isFocused: Bool var body: some View { VStack { TextField("TextField", text: .constant("")) .focused($isFocused) Button("HIDE KEYBOARD") { isFocused = false } Spacer() Button("ACTION") { url = URL(string: "https://google.com") } } .sheet(item: $url) { value in NavigationStack { WebView(url: value) .toolbar { ToolbarItem(placement: .topBarLeading) { Button("CLOSE") { url = nil } } } } } } } extension URL: Identifiable { public var id: String { absoluteString } }
1
3
665
2w
.tint() has no effect on macOS Liquid Glass toggles (on state background)
Environment: • macOS 26.0 (25A354) • Xcode 26.0.1 (17A400) Issue: Applying .tint(...) to a macOS Liquid Glass style Toggle does not change the background color when the toggle is in the on state. Expected behavior: The .tint(...) modifier should apply the chosen color. Actual behavior: The toggle remains system blue (accent color), regardless of the tint specified Notes: I’m hearing that .tint() behaves normally on iOS, so this may be macOS-specific.
1
1
104
2w
SwiftUI: Can a NavigationDestination in NavigationStack present the view as a .sheet instead of pushing?
Hi everyone, I’m experimenting with SwiftUI's new NavigationStack / navigationDestination API. Normally, when you navigate to a value using NavigationLink(value:) and a matching navigationDestination(for:), the destination view is pushed onto the navigation stack. What I’d like to know is: Is there a way to present that destination view as a sheet instead of pushing it? Essentially: Can a NavigationDestination be shown modally? Here’s a simplified example of what I mean: struct RootView: View { var body: some View { NavigationStack { NavigationLink(value: "Example") { Text("Push me!") } .navigationDestination(for: String.self) { _ in DetailView() // <--- Can this be shown as a sheet? } } } } My questions are: Is there a built‑in way to make a navigationDestination present modally (as .sheet) instead of pushing? If not, is the recommended approach to handle .sheet state manually outside of the NavigationStack and bypass navigationDestination for such cases? Can the NavigationPath itself somehow encode a modal presentation style for certain types? Thanks in advance for any tips or confirmation that this is (not) possible in SwiftUI.
0
0
82
2w