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

Snippet Views don't render consistently, width not always respected
I've created a Snippet for my iOS app which I want to be able to run from the LockScreen via a Shortcuts widget. All works fine except when I run the shortcut and the App Snippet appears, it doesn't always render the SwiftUI view in the same way. Sometimes the width boundaries are respected and sometimes not. I've tested this on iOS 26.1 and iOS 26.2 beta 3 I think this is a bug but it would be great if anyone could see what I might be doing wrong if it's not. Incase it is a bug I've filed a feedback (FB21076429) and I've created a stripped down sample project showing the issue and added screenshots showing the issue. Basic code to reproduce issue: // Intent.swift // SnippetBug import AppIntents import Foundation import SwiftUI struct SnippetEntryIntent: AppIntent { static let title: LocalizedStringResource = "Open Snippet" static let description = IntentDescription("Shows a snippet.") // Don’t open the app – stay in the snippet surface. static let openAppWhenRun: Bool = false func perform() async throws -> some ShowsSnippetIntent { .result(snippetIntent: TestSnippetIntent()) } } struct TestSnippetIntent: SnippetIntent { static let title: LocalizedStringResource = "Snippet Intent" static let description = IntentDescription("Action from snippet.") @MainActor func perform() async throws -> some IntentResult & ShowsSnippetView { .result(view: SnippetView(model: SnippetModel.shared)) } } @MainActor final class SnippetModel { static let shared = SnippetModel() private init() { } } struct SnippetView: View { let model: SnippetModel var body: some View { HStack { Text("Test Snippet with information") Spacer() Image(systemName: "heart") }.font(.headline) } } struct Shortcuts: AppShortcutsProvider { static var appShortcuts: [AppShortcut] { AppShortcut( intent: SnippetEntryIntent(), phrases: [ "Snippet for \(.applicationName)", "Test Snippet \(.applicationName)" ], shortTitle: "Snippet", systemImageName: "barcode" ) } } You also need these lines in your main App entry point: import AppIntents @main struct SnippetBugApp: App { init() { let model = SnippetModel.shared AppDependencyManager.shared.add(dependency: model) } var body: some Scene { WindowGroup { ContentView() } } } This is correct This is incorrect
0
0
18
3h
Severe Scroll Lag & Header Flickering in Complex SwiftUI Screen with Dynamic Content (GeometryReader + Scroll Direction Detection)
I’m working on a SwiftUI screen where I need to hide a header when the user scrolls down and show it again when the user scrolls up. I’m currently using a ScrollView combined with GeometryReader to detect scroll offset changes and update state variables like isScrolling or isScrollingDown. The issue is that the behavior is inconsistent. When I scroll down, the header hides correctly, but when I scroll back up, the header often doesn’t appear again even though the offset is changing. Sometimes the header comes back with a delay, and other times it never appears at all. Along with this, I’m also seeing noticeable UI lag whenever I try to calculate content height or read multiple geometry values inside the ScrollView. It looks like the frequent state updates inside the scroll offset tracking are causing layout recalculations and frame drops. I’ve tried placing the header in different positions (inside a ZStack aligned to the top, inside the VStack above the ScrollView, and with transitions like .push(from: .top)), but the result is still the same: smooth scrolling breaks, and the header doesn’t reliably animate back when scrolling upward. What I’m looking for is a minimal and efficient approach to detect scroll direction and trigger the header hide/show animation without causing performance issues or recomputing expensive layout values. Any guidance or a simplified pattern that works well for dynamic headers in SwiftUI would be very helpful. if isScrolling { headerStackView() //Includes Navigation Bar .transition( .asymmetric( insertion: .push(from: .top), removal: .push(from: .bottom) ) ) } GeometryReader { outer in let outerHeight = outer.size.height ScrollView(.vertical) { VStack { content() // Heavy view + contains its own ScrollView } .background { GeometryReader { proxy in let contentHeight = proxy.size.height let minY = max( min(0, proxy.frame(in: .named("ScrollView")).minY), outerHeight - contentHeight ) if #available(iOS 17.0, *) { Color.clear .onChange(of: minY) { oldVal, newVal in // Scroll direction detection if (isScrolling && newVal < oldVal) || (!isScrolling && newVal > oldVal) { isScrolling = newVal > oldVal } } } } } } .coordinateSpace(name: "ScrollView") } .padding(.top, 1)
0
0
18
6h
iOS 26.1 adds dark tint under transparent tab bar and ui elements (worked correctly in iOS 26)
After updating from iOS 26 to iOS 26.1, all my transparent system elements (i.e. UITabBar, UIBarButtonItem) started rendering with a dark background tint. In iOS 26 the same configuration looked fully transparent / glassy. The strange part is that the tint only appears in normal UIViewControllers. In UITableViewController the tab bar still looks correct and transparent, even on iOS 26.1. I am using the same appearance code as before: func setupTabBarAppearance() { guard let tabBar = tabBarController?.tabBar else { return } if #available(iOS 26.0, *) { let appearance = UITabBarAppearance() appearance.configureWithTransparentBackground() appearance.backgroundColor = .clear appearance.backgroundEffect = nil appearance.shadowColor = .clear tabBar.standardAppearance = appearance tabBar.scrollEdgeAppearance = appearance tabBar.isTranslucent = true tabBar.backgroundColor = .clear tabBar.barTintColor = .clear } else { tabBar.isTranslucent = true tabBar.backgroundImage = UIImage() tabBar.shadowImage = UIImage() tabBar.backgroundColor = .clear } } I tried removing backgroundEffect, forcing .clear colors, using configureWithDefaultBackground, changing edgesForExtendedLayout, extendedLayoutIncludesOpaqueBars, etc. I noticed that if I change Liquid Glass in iOS 26 settings from Clear to Tinted, then I get a black tint everywhere and the interface becomes consistent, but not the way I want. Nothing removes the new dark tint in iOS 26.1. Is this an intentional change in iOS 26.1, a bug, or is there a new way to make the tab bar fully transparent again?
0
0
22
6h
how to navigate programmatically without navigation link?
Hello. I'm making an app with several different views. I'm trying to switch views using a button but I can't seem to figure out how. I know Navigation Links work, but my case doesn't work. The reasons for this are because I need to run other code when they click the button and I don't want them to be able to navigate back (to CustomizationView/CreateAccountView). I know that you can hide the back button but my problem with that is the fact that i will be navigating to a view (MainView) that will also have navigation buttons in it, so if i'm thinking correctly, the button will be hidden but when they press the next navigationlink (in MainView) it will show again and then they can go back (to CustomizationView/CreateAccountView). i don't want them to go back because they will be navigating from a login/account view that wont be needed anymore. I'm currently using .fullScreenCover() and it works fine except for performance (I'm assuming). here's the code: import SwiftUI struct CustomizationView: View { @State private var showMain = false var body: some View { Button("Done") { // some more code here showMain = true } .fullScreenCover(isPresented: $showMain) { MainView() } } } here's a visual for the navigation if you're confused
1
0
63
13h
SwiftUI Sheet view with @Query loses model context
I've run into a strange issue. If a sheet loads a view that has a SwiftData @Query, and there is an if statement in the view body, I get the following error when running an iOS targetted SwiftUI app under MacOS 26.1: Set a .modelContext in view's environment to use Query While the view actually ends up loading the correct data, before it does, it ends up re-creating the sqlite store (opening as /dev/null). The strange thing is that this only happens if there is an if statement in the body. The statement need not ever evaluate true, but it causes the issue. Here's an example. It's based on the default xcode new iOS project w/ SwiftData: struct ContentView: View { @State private var isShowingSheet = false var body: some View { Button(action: { isShowingSheet.toggle() }) { Text("Show Sheet") } .sheet(isPresented: $isShowingSheet, onDismiss: didDismiss) { VStack { ContentSheetView() } } } func didDismiss() { } } struct ContentSheetView: View { @Environment(\.modelContext) private var modelContext @Query public var items: [Item] @State var fault: Bool = false var body: some View { VStack { if fault { Text("Fault!") } Button(action: addItem) { Label("Add Item", systemImage: "plus") } List { ForEach(items) { item in Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard)) } } } } private func addItem() { withAnimation { let newItem = Item(timestamp: Date()) modelContext.insert(newItem) } } } It requires some data to be added to trigger, but after adding it and dismissing the sheet, opening up the sheet with trigger the Set a .modelContext in view's environment to use Query. Flipping on -com.apple.CoreData.SQLDebug 1 will show it trying to recreate the database. If you remove the if fault { Text("Fault!") } line, it goes away. It also doesn't appear to happen on iPhones or in the iPhone simulator. Explicitly passing modelContext to the ContentSheetView like ContentSheetView().modelContext(modelContext) also seems to fix it. Is this behavior expected?
0
0
75
15h
Unable to create SwiftUI previews in Xcode 26 for iOS 15.5
I am getting this error msg when I try to run a SwiftUI Preview on an iOS 15.5 simulator: Termination Reason: Namespace DYLD, Code 1, Library missing | Library not loaded: /usr/lib/swift/libswift_StringProcessing.dylib | Referenced from: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/libLiveExecutionResultsLogger.dylib | Reason: tried: '/Users/hfg/Library/Developer/Xcode/DerivedData/Testios15sim-aawlbfbtggzozseoekycwwpadhrc/Build/Intermediates.noindex/Previews/iphonesimulator/Testios15sim/Products/Debug-iphonesimulator/libswift_StringProcessing.dylib' (no such file), '/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 15.5.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswift_StringProcessing.dylib' (no such file), '/usr/lib/swift/libswift_StringProcessing.dylib' (no such file), '/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 15.5.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libswift_StringProcessing.dylib' (no such file) FYI I tried with the Legacy Preview Execution both on and off
1
0
88
18h
Request Review alert is unresponsive in iOS 26.1
Try this simple code: import SwiftUI import StoreKit struct ReviewView: View { @Environment(\.requestReview) var requestReview var body: some View { Button("Leave a review") { requestReview() } } } When the Review Alert shows, the "Not Now" button is disabled for some reason!? It was always tappable in all iOS versions that I remember. And there is no way to opt out, unless the user taps on the stars first. Is it a bug or a feature? Thanks for looking into it!
1
0
153
20h
TimelineView using ExplicitTimelineSchedule ignores last date?
Hi, everyone. I'm trying my first TimelineView with an explicit schedule, but my attempt – and even the simple example from the documentation – doesn't seem to work as documented. Here's what the documentation says an explicit schedule does: The timeline view updates its content on exactly the dates that you specify, until it runs out of dates, after which it stops changing. And it gives this example: let dates = [ Date(timeIntervalSinceNow: 10), // Update ten seconds from now, Date(timeIntervalSinceNow: 12), // and a few seconds later. ] struct MyView: View { var body: some View { TimelineView(.explicit(dates)) { context in Text(context.date.description) } } } There are stipulations about what the view – which always displays some version of its content body – will do given only past or future dates, but it seems clear we should expect the view in this example to redraw at least once after it appears. Here's the rest of the discussion from the documentation with my comments after testing what's stated: If the dates you provide are in the past, the timeline view updates exactly once with the last entry. That seems true, considering the "update" to be the initial draw. If you only provide dates in the future, the timeline view renders with the current date until the first date arrives. Not exactly: it looks the "date" property of the initial render is the (future) date of the first schedule entry, even though it's drawn early. When the first date does arrive, the body closure doesn't seem to be called. Only on the next date, if there is one, is it called again. If you provide one or more dates in the past and one or more in the future, the view renders the most recent past date, refreshing normally on all subsequent dates. That also seems correct, except… … that in every scenario, the final date entry seems to be ignored completely! In other words, unless all date entries are in the past, the Timeline View stops before it runs out of dates. That documented example from the start, which we expect to redraw at least once after it appears? When I test it in a Playground, it appears, but doesn't redraw at all! So, that's my main point of confusion after experimenting with TimelineView for the first time. I can achieve my own goal by appending an extra entry to my explicit schedule – even appending an entry identical to the previous "final" entry seems to work – but naturally that leaves me unclear about why I need to. If anyone can tell me what I'm not understanding, I'd be grateful.
3
2
780
20h
Layout issues occur when the Picker style is segmented on macOS.
When I run the following code and change "Is On", I get a problem with the layout of the Picker. There is no problem when using Text(), but when using only Image, it works fine on iOS but there is a problem on macOS. Tested on macOS 26.1, Xcode 26.1. import SwiftUI struct ContentView: View { @State var model = Model() var body: some View { Form { Picker("Category", selection: $model.category) { ForEach(Category.allCases) { item in Image(systemName: item.icon) .tag(item) } } .pickerStyle(.segmented) Toggle("Is On", isOn: $model.isOn) } .formStyle(.grouped) } } struct Model { var category: Category = .a var isOn: Bool = false } enum Category: Int, Identifiable, CaseIterable { case a, b, c var id: Int { rawValue } var icon: String { switch self { case .a: return "a.circle.fill" case .b: return "b.circle.fill" case .c: return "c.circle.fill" } } var name: String { switch self { case .a: return "a" case .b: return "b" case .c: return "c" } } } code-block
1
0
15
20h
TabView + NavigationStacks broken on iOS 26.1
Broken TabView + NavigationStacks functionality on iOS 26.1. Even the most basic navigation made impossible. Example: TabView { Tab(...) { NavigationStack(path: $homePath) { HomeView() .navigationDestination { ... } } } Tab(...) { NavigationStack(path: $settingsPath) { SettingsView() .navigationDestination { ... } } } } Anything passed to settingsPath is just ignored and would never appear onscreen. (26.0 and prior versions work as expected.) Are there any workarounds?
1
0
47
21h
SwiftUI .toolbar(placement: .keyboard) item not exposed to accessibility on iOS 26.1 (affects VoiceOver + XCUITest)
Description On iOS 26.1, a ToolbarItem placed in .keyboard is no longer exposed to the accessibility hierarchy. As a result: VoiceOver cannot focus or activate the toolbar button XCUITest cannot discover the element, making the UI impossible to test TextEditor() .toolbar { ToolbarItem(placement: .keyboard) { Button("Done") { /* action */ } } } This worked correctly on previous iOS versions. The button appears visually but is missing from both VoiceOver navigation and XCUI accessibility queries. Steps to Reproduce Create a new SwiftUI project. Use a simple text field with a keyboard toolbar button. Run on an iOS 26.1 device or simulator. Focus the text field to show the keyboard. Turn on VoiceOver and attempt to navigate to the toolbar button. Run an XCUITest attempting to locate the button
1
0
30
21h
iOS Dark mode Liquid Glass Tab bar with Reduce Transparency Issue
Hi, I have an iOS app that I’m trying to update with Liquid Glass. In this app, I’m using a tab bar, which works fine with Liquid Glass, but as soon as I enable the “Reduce Transparency” setting in dark mode, I get a strange effect: at launch, the tab bar appears correctly in dark mode, but after scrolling a bit in the view, it eventually switches to light mode 😅 At launch: After a bit of scrolling: I can’t figure out whether this is intended behavior from the framework or not (I don’t have this issue with other apps). I can reproduce it in a project built from scratch, here is the code (don't forget to set dark mode to the device and activate the reduce transparency option in the accessibility menu): struct ContentView: View { var body: some View { TabView { ScrollView { LazyVStack { ForEach(0..<100) { _ in Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello world").foregroundStyle(.primary) } } .padding() } .tabItem { Label("Menu", systemImage: "list.dash") } } } } Do you know if this is expected behavior? Or if there’s something that can be done about it? Thanks,
1
0
65
1d
refreshable modifier causes misaligned button tap targets in ScrollView
I have a ScrollView with several Buttons and a .refreshable modifier. As soon as I pull to refresh and the refresh indicator appears, the tap targets no longer match the visible button positions. For example, tapping button A triggers button B’s action, as if the hit-testing region didn’t move along with the content. This only happens while the refresh indicator is shown. Before pulling to refresh, everything is correct and afterwards as well. Tested on iOS 18 and 26 (Xcode 16.4, Xcode 26). Here is a minimal reproducible example: import SwiftUI struct ContentView: View { var body: some View { ScrollView { VStack { Button("Button A") { print("A") } .buttonStyle(.borderedProminent) Button("Button B") { print("B") } .buttonStyle(.borderedProminent) Button("Button C") { print("C") } .buttonStyle(.borderedProminent) Button("Button D") { print("D") } .buttonStyle(.borderedProminent) Button("Button E") { print("E") } .buttonStyle(.borderedProminent) } .frame(maxWidth: .infinity) } .refreshable { try? await Task.sleep(for: .seconds(60)) } } }
2
0
70
1d
How Do Commercial Apps Extract Screen Time Data on iOS?
Looking at Brainrot's UI, they display both "Screen Time: 6h 31m" and a calculated "Health: 91/100" score with a "Tap to Fix" button. This suggests manual sync or a workaround. Specific Questions: Can DeviceActivityReport extensions communicate data back to the main app? (CloudKit, Notifications, Shared files?) Can extensions write to UserDefaults on physical devices? Do commercial apps rely on manual user sync? Is there an alternative API I'm overlooking? Do threshold-based approximations work reliably for daily tracking? I can extract exact minutes in the extension but can't export them to the main app due to sandbox restrictions. Either a technical solution or confirmation that manual sync is the industry standard would help greatly.
1
0
26
1d
NavigationSplitView and NavigationStack persistence
Let's say you have a NavigationModel that contains three NavigationPaths, one for each option in the sidebar for a NavigationSplitView. This NavigationModel is created by the App and passed down to the root view for the scene in its environment. Each option has a separate NavigationStack and is passed a binding to the appropriate NavigationPath from the NavigationModel. Is it expected that when the user changes the selection in the sidebar, the NavigationPath for the newly selected view should be erased? This is what's currently happening on macOS 26. It seems like the default action when creating a NavigationStack and passing it a binding to a NavigationPath is to clear that path and start from the root view. Is this normal, intended behaviour or is it a bug? Or, perhaps, an option or modifier I am missing?
3
0
196
3d
NSButton + TtGC6AppKit18_NSCoreHostingViewVS_12AppKitButton - Image Alignment Changed/Broken in Minor macOS 26.1 Update
I just updated to macOS 26.1. I have a pure AppKit app (I guess that's not possible anymore but as close to a pure AppKit app as you can get). I use NSButton with the glass bezel style and SF symbol images. It looks like the minor OS update brought layout changes because now some of these buttons are scaling the symbol image much larger than was being done on macOS 26. The image can sometimes draw outside the glass 'bezel'. It looks like using the 'info' symbol in a button results in much larger image scaling than it did on the previous Tahoe for some SF Symbols. With the glass bezel style and a SF Symbol image how am I supposed to consistently make the button look good? With certain symbols I have to use imageScaling NSImageScaleProportionallyUpOrDown and on others I have to use NSImageScaleProportionallyDown. If I'm using a system image shouldn't it just do the right thing? Is trial and error the only way to tell? That's what I was doing before but it seems that the minor 26.1 update changed things. Additionally calling -sizeToFit on a button multiple times can cause it to shrink for example: [button sizeToFit]; // <-- At fitting size // Then later [button sizeToFit]; // Now button is shrunk But if the button is already at its fitting size an additional call later shouldn't make it shrink, it should stay the same size. FB20517174 I see I now inherit SwiftUI, not sure if that has anything to do with this but if I wanted to opt in to fragile layout I wouldn't be using Appkit...
1
0
45
4d
proxy.ScrollTo Unitpoint Y Value uses negative tenths for positioning?
I am using a ScrollViewReader, ScrollView, LazyVStack to organize a list of elements I want to be able to scroll to a specific location so i use elementID in the list and a UnitPoint value. But the y value for unitpoint uses -0.1 to represent 100%. Is this intended behavior, a bug, or am i using something incorrectly? I could not find this in the docs and it was only after debugging I found that proxy.scrollTo(id, UnitPoint(x:0, y:-0.1)) is how you scroll to the end of an item or proxy.scrollTo(id, UnitPoint(x:0, y:-0.05)) to scroll to the center. Am I accessing the scrollTo property wrong or is this just how we use it? Also it seems .bottom is broken due to this aswell (as it uses 1 but the actual value that scrolls to the bottom is -0.1). This seems like unintended behvaior as UnitPoints are supposed to be have values of 0-1 Here is a view which reproduces this behavior struct ScrollTestView: View { @State private var scrollToId: String = "" @State private var scrollToAnchorY: String = "0.0" @State private var scrollProxy: ScrollViewProxy? var body: some View { VStack { HStack(spacing: 12) { TextField("Enter ID (1-30)", text: $scrollToId) .frame(width: 120) .padding(8) .background(Color.gray.opacity(0.1)) .cornerRadius(8) TextField("Anchor Y (0-1)", text: $scrollToAnchorY) .frame(width: 120) .padding(8) .background(Color.gray.opacity(0.1)) .cornerRadius(8) Button { guard let targetId = Int(scrollToId), let anchorY = Double(scrollToAnchorY), let proxy = scrollProxy else { return } let anchorPoint = UnitPoint(x: 0.5, y: anchorY) proxy.scrollTo(targetId, anchor: anchorPoint) } label: { Text("Scroll") .font(.subheadline) .padding(.horizontal, 16) .padding(.vertical, 8) .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } Spacer() } .padding(.horizontal, 16) .padding(.vertical, 8) ScrollViewReader { proxy in ScrollView { LazyVStack { ForEach(1...30, id: \.self) { itemId in VStack { HStack { Text("Item \(itemId)") .font(.title2) .bold() Spacer() } .padding(.vertical, 16) Divider() .background(Color.gray.opacity(0.6)) } .id(itemId) } } .padding() } .onAppear { scrollProxy = proxy } } } } }
0
0
29
4d