Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

SwiftUI Documentation

Posts under SwiftUI subtopic

Post

Replies

Boosts

Views

Activity

PresentationDetent to auto-size sheet to the height of the contained Views
(Also submitted as FB19359821) I suggest a PresentationDetent.sizeToFit or PresentationDetent.contentSize that automatically sizes the sheet to the height of the contained Views. This seems to be a common requirement for many app developers and it would be nice if this would be supported out of the box without fiddling around with the usual GeometryReader in background -> make available the height with a preference key -> .presentationDetents([.height(…)]) workarounds.
Topic: UI Frameworks SubTopic: SwiftUI
0
1
39
Aug ’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.
0
0
51
Aug ’25
Change iOS Keyboard Language without adding to Settings > Keyboards
The first-party Apple Translate app will switch the on-screen keyboard to the selected language, even when the keyboard for that language is NOT added in Settings > General > Keyboards. We'd like to mirror this behavior and switch the keyboard for input based on a user-selected language from a drop-down without the user needing to add that language to Keyboards I'm struggling to find if this behavior is achieved via a public API. Any insights here?
1
0
45
Aug ’25
On macOS, how do you place a toolbar item on the trailing edge of the window's toolbar when an Inspector view is open?
Using SwiftUI on macOS, how can I add a toolbar item on the right-most (trailing) edge of the window's toolbar when an Inspector is used? At the moment, the toolbar items are all left-of (leading) the split view tracking separator. I want the inspector toolbar item to be placed similar to where Xcode's Inspector toolbar item is placed: always as far right (trailing) as possible. NavigationSplitView { // ... snip } detail: { // ... snip } .inspector(isPresented: $isInspectorPresented) { InspectorContentView() } .toolbar { // What is the correct placement value here? ToolbarItem(placement: .primaryAction) { Button { isInspectorPresented.toggle() } label: { Label("Toggle Inspector", systemImage: "sidebar.trailing") } } } See the attached screenshot. When the InspectorView is toggled open, the toolbar item tracks leading the split view tracking separator, which is not consistent with how Xcode works.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
4
0
73
Aug ’25
.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) } } } } }
4
1
184
Aug ’25
SWIFTU UI - Graph package similar to Neo4J GUI
Is there a good library / opensource package for Graph library similar to Neo4J GUI (pl.see attached) I tried few of the below, looking for something better https://medium.com/better-programming/building-a-graph-with-swiftui-b16dc48f7fe6 https://github.com/palle-k/Graphite
Topic: UI Frameworks SubTopic: SwiftUI
1
0
95
Aug ’25
When removing a ToolbarItem from the navigation bar, how do I make the remaining ToolbarItems resize correctly?
Because .searchable does not allow for customizing buttons in the search bar, I've manually had to recreate the search bar as shown below. However, when removing one of the items in the search bar, the TextField does not resize correctly and effectively inserts padding on the leading edge. When the TextField is focused, it resizes and fills the entire space. If the "Compose" button was already hidden when the search bar is presented, it lays out correctly. How do I resize the TextField after removing the "Compose" button automatically? Thanks, jjp struct ContentView: View { @State var isSearchBarVisible = false @State var isComposingMessage = false @State var searchText = "" let items: [String] = ["hey", "there", "how", "are", "you"] var searchItems: [String] { items.filter { item in item.lowercased().contains(searchText.lowercased()) } } var body: some View { NavigationStack { VStack { List { if !searchText.isEmpty { ForEach(searchItems, id: \.self) { item in Text(item) } } else { ForEach(items, id: \.self) { item in Text(item) } } } } .toolbar { if isSearchBarVisible { ToolbarItem(placement: .principal) { TextField("Search", text: $searchText) .padding(8) .background(Color.gray.opacity(0.2)) } ToolbarItem(placement: .topBarTrailing) { Button(action: { isSearchBarVisible = false },[![enter image description here][1]][1] label: { Text("Cancel") }) } if !isComposingMessage { ToolbarItem(placement: .topBarTrailing) { Button(action: { isComposingMessage.toggle() }, label: { Text("Compose") }) } } } else { ToolbarItem(placement: .topBarLeading) { Button(action: { isSearchBarVisible = true }, label: { Text("Search") }) } ToolbarItem(placement: .principal) { Text("Title") } ToolbarItem(placement: .topBarTrailing) { Button(action: { isComposingMessage.toggle() }, label: { Text("Compose") }) } } } } } }
1
0
83
Aug ’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.
1
1
162
Aug ’25
.contentMargins(.top, 0, for: .scrollContent) has no effect on .plain List with section headers (iOS 17 & 18)
I'm trying to remove the extra top padding from the first section of a SwiftUI List using .plain style. I applied: .contentMargins(.top, 0, for: .scrollContent) But it seems to have no effect on iOS 17 and iOS 18.5 when section headers are present. However, it does work correctly on iOS 26 (tested with the latest Xcode beta). Has anyone else run into this? Is this a known issue or regression in iOS 17/18? Is there any reliable workaround to remove or reduce the top padding in .plain list style when using section headers? I have screenshots comparing iOS 18.5 and iOS 26 if needed. Thanks in advance!
1
0
71
Aug ’25
SwiftUI Navigation - Top toolbar breaks and app is unusable
We've been trying to track down a non-reproducible issue for the past few months, and I'm wondering if anybody has encountered the same one. Screenshots of the issue attached here. As you can see, the toolbar isn't respecting the safe area; there are many more issues that occur when this bug happens as well, such as the app being extremely laggy and sheets not opening. Anecdotally, this seems to happen if the app is opened after not having been opened in a while (say, a day or so). It tends to happen first thing in the morning when I open the app, but as I mentioned, it's been very hard to reproduce. I'm also wondering if it's a known SwiftUI navigation issue or if anyone has encountered this.
2
0
99
Jul ’25
VisionOS: WKWebView stops rendering after WindowGroup is closed
I'm building a visionOS app where users can place canvases into the 3D environment. These canvases are RealityKit entities that render web content using a WKWebView. The web view is regularly snapshotted, and its image is applied as a texture on the canvas surface. When the user taps on a canvas, a WindowGroup is opened that displays the same shared WKWebView instance. This works great: both the canvas in 3D and the WindowGroup reflect the same live web content. The canvas owns the WKWebView and keeps a strong reference to it. Problem: Once the user closes the WindowGroup, the 3D canvas stops receiving snapshot updates. The snapshot loop task is still running (verified via logs), but WKWebView.takeSnapshot(...) never returns — the continuation hangs forever. No error is thrown, no image is returned. If the user taps the canvas again (reopening the window), snapshots resume and everything works again. @MainActor private func getSnapshot() async -> UIImage? { guard !webView.isLoading else { return nil } let config = WKSnapshotConfiguration() config.rect = webView.bounds config.afterScreenUpdates = true return await withCheckedContinuation { continuation in webView.takeSnapshot(with: config) { image, _ in continuation.resume(returning: image) } } } What I’ve already verified: The WKWebView is still in memory. The snapshot loop (Task) is still running; it just gets stuck inside takeSnapshot(...). I tried keeping the WKWebView inside a hidden UIWindow (with .alpha = 0.01, .windowLevel = .alert + 1, and isHidden = false). Suspicion It seems that once a WKWebView is passed into SwiftUI and rendered (e.g., via UIViewRepresentable), SwiftUI takes full control over its lifecycle. SwiftUI tells WebKit "This view got closed" and WebKit reacts by stopping the WKWebView. Even though it still exists in memory and is being hold by a strong reference to it in the Canvas-Entity. Right now, this feels like a one-way path: Starting from the canvas, tapping it to open the WindowGroup works fine. But once the WindowGroup is closed, the WebView freezes, and snapshots stop until the view is reopened. Questions Is there any way under visionOS to: Keep a WKWebView rendering after its SwiftUI view (WindowGroup) is dismissed? Prevent WebKit from suspending or freezing the view? Embed the view in a persistent system-rendered context to keep snapshotting functional? For context, here's the relevant SwiftUI setup struct MyWebView: View { var body: some View { if let webView = WebViewManager.shared.getWebView() { WebViewContainer(webView: webView) } } } struct WebViewContainer: UIViewRepresentable { let webView: WKWebView func makeUIView(context: Context) -> UIView { return webView } func updateUIView(_ uiView: UIView, context: Context) {} }
1
0
135
Jul ’25
Tinting/Coloring tabs when using SidebarAdaptableTabViewStyle like List
SwiftUI.List allows for customization using .listItemTint, .tint, or .foregroundStyle. This can be used to color individual items in the list, other than the app's specified accent color. Is there an equivalent feature to customize individual Tab's icon or label, when using TabView's SidebarAdaptableTabViewStyle, and its in the sidebar style. From what I understand, there needs to be a modifier applied directly to Tab unlike List, and not just the label. Since there isn't any color/tint modifiers, is it not possible?
1
0
53
Jul ’25
Mitigating overlapping text for sticky section headers for a plain List in iOS 26
When preparing SwiftUI code that uses List with .listStyle(.plain) for iOS 26, the by-default sticky section headers combined with the new translucent top-bars often causes unpleasantly overlapping text: Two questions here: Is there a modifier to make section headers non-sticky? This would be helpful for cases where the translucent bar is a good fit and the section titles don't need to be sticky/pinned. I found .listStyle(.grouped) can be an alternative in some cases, but this adds a gray background / additional padding to the section titles. Is there a way to get a blurry material behind the section headers when they are sticking to the top bar? This would be good for cases where the section header is important content-wise (like in the two-column example above or for a data list categorized using sections that should be always visible as a point of reference) I found the scroll edge effects and .scrollEdgeEffectStyle(.hard, for: .top) does the trick for the top bar but doesn't affect attached sticky section headers (maybe it should?). Also I played around with .toolbarBackground(...) but this didn't do anything useful for a nav bar in my experiments.
Topic: UI Frameworks SubTopic: SwiftUI
5
0
129
Jul ’25
ProductView failed to trigger purcahse flow.
Hi, My app has an IAP and the view that let user to purchase is simply a ProductView. The purchase flow should be handled by the ProductView itself. I have tested the app with xcode storekit configuration, xcode run with sandbox account and also TestFlight environment as well. The purchase is triggered and the app feature is unlocked after purchase. However, I keep getting app review team feedback with the following problem: Bug description: the purchase button is greyed out after we tapped on it, however, there's no purchase flow popped up I have tried multiple things. Building with xcode cloud, removing the storekit configuration from the build scheme. But none can get the app review team to get through the problem. The IAP is not available in certain region. In that case, the app will show a message. However, the app review attached an screenshot which shows the product view. The view that allow users to purchase if let product = store.products.first(where: { $0.id == "com.xxx.xxxxxxx" }) { // If the product is available, show the ProductView ProductView(id: product.id) .productViewStyle(.compact) } else { // If the product is not available, show a message Text("In-app purchase is not available in your region.") } The store class @Published private(set) var products: [Product] = [] ... init() { //To handle the parental approval flow getUpdateTransaction() } func getUpdateTransaction() { updates = Task { for await update in StoreKit.Transaction.updates { if let transaction = try? update.payloadValue { await fetchActiveTransactions() await transaction.finish() } } } } Does anyone what can go wrong with ProductView? As this is part of the StoreKit API, I don't know what can go wrong. At least the purchase flow should be covered by it. Also, is sandbox and TestFlight a good way to test IAP? Thanks!
1
0
50
Jul ’25
How to opt out of tinting content in visionOS widgets
During the WWDC Session called "Design widgets for visionOS" the presenter says: You can choose whether the background of your widget participates in tinting. If you opted out, for example to preserve a photo or illustration, make sure it still looks good alongside the selected color palette. https://developer.apple.com/videos/play/wwdc2025/255 Unfortunately, this session has no example code. Can someone point me to the correct way to do this? Is there a modifier we can use on views? When a user selects one the tint colors using the configuration screen, we would like to prevent some views from being tinted.
0
0
58
Jul ’25
Hide search field always
Greetings, Please type slowly, I'm new at this. iOS 18.x. Added search to a list, visibility toggled with a toolbar button, using this line of code: .searchable(text: $searchText, isPresented: $isSearchPresented, placement: .navigationBarDrawer(displayMode: .automatic), prompt: "Search...") Realized I was re-stating defaults, changed it to this: .searchable(text: $searchText, isPresented: $isSearchPresented, prompt: "Search...") In both cases, it works great when in the middle of the list, just like I wanted. However, when I scroll to the top of the list, the serach field is displayed even when 'isPresented' is false. Is there any way to keep the search field hidden even at the top of the list? ..thanks!
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2
0
104
Jul ’25
iOS26: Programmatically Minimize TabView
In our app we have a view with a custom scroll implementation in a TabView. We would like to programmatically minimize (not hide) the TabView, like .tabBarMinimizeBehavior(...) does when a List is behind the tab bar and a user scrolls. I haven't found any view modifier that I can attach that allows me to do so, is this not possible? I would have expected something like .tabBarMinimized($tabBarMinimized)
Topic: UI Frameworks SubTopic: SwiftUI
0
0
83
Jul ’25