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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

How to hide moreNavigationController in SwiftUI?
I have more than five tabs in a TabView, and on some screens, I'm seeing a navigation bar with the title "More". I understand that this is the default behavior of TabView when there are more than five tabs—iOS automatically creates a "More" screen. I've set navigationBarHidden = true throughout my app, but the navigation bar still appears on some screens within the "More" section. Is there another way to hide the moreNavigationController or completely remove the navigation bar from the "More" screen?
0
0
111
Jul ’25
SwiftUI Table performance issue
I found the Table with Toggle will have performance issue when the data is large. I can reproduce it in Apple demo: https://developer.apple.com/documentation/swiftui/building_a_great_mac_app_with_swiftui Replace with a large mock data, for example database.json Try to scroll the table, it's not smooth. I found if I delete the Toggle, the performance be good. TableColumn("Favorite", value: \.favorite, comparator: BoolComparator()) { plant in Toggle("Favorite", isOn: $garden[plant.id].favorite) .labelsHidden() } Is this bug in SwiftUI? Any workaround? My Mac is Intel, not sure it can repro on Apple Silicon
2
0
297
Jul ’25
iOS 16.0 beta 7 broke Text(Date(), style: .timer) in SwiftUI widgets
Hi, In my apps, the recent iOS 16.0 beta 7 (20A5356a) broke the .timer DateStyle property of the Text view, in a SwiftUI widget. In previous OS and beta, Text(Date(), style: .timer) was correctly displaying an increasing counter. In iOS 6.0 beta 7, Text(Date(), style: .timer) does not update anymore, (and is offset to the left). The other DateStyle (like .offset, .relative, ...) seems to update correctly. Anyone noticed that (very specific) problem ?
39
14
11k
Jul ’25
SwiftUI scroll position targeting buggy with viewAligned scrollTargetBehavior
I have a discrete scrubber implementation (range 0-100) using ScrollView in SwiftUI that fails on the end points. For instance, scrolling it all the way to bottom shows a value of 87 instead of 100. Or if scrolling down by tapping + button incrementally till it reaches the end, it will show the correct value of 100 when it reaches the end. But now, tapping minus button doesn't scrolls the scrubber back till minus button is clicked thrice. I understand this has only to do with scroll target behaviour of .viewAligned but don't understand what exactly is the issue, or if its a bug in SwiftUI. import SwiftUI struct VerticalScrubber: View { var config: ScrubberConfig @Binding var value: CGFloat @State private var scrollPosition: Int? var body: some View { GeometryReader { geometry in let verticalPadding = geometry.size.height / 2 - 8 ZStack(alignment: .trailing) { ScrollView(.vertical, showsIndicators: false) { VStack(spacing: config.spacing) { ForEach(0...(config.steps * config.count), id: \.self) { index in horizontalTickMark(for: index) .id(index) } } .frame(width: 80) .scrollTargetLayout() .safeAreaPadding(.vertical, verticalPadding) } .scrollTargetBehavior(.viewAligned) .scrollPosition(id: $scrollPosition, anchor: .top) Capsule() .frame(width: 32, height: 3) .foregroundColor(.accentColor) .shadow(color: .accentColor.opacity(0.3), radius: 3, x: 0, y: 1) } .frame(width: 100) .onAppear { DispatchQueue.main.async { scrollPosition = Int(value * CGFloat(config.steps)) } } .onChange(of: value, { oldValue, newValue in let newIndex = Int(newValue * CGFloat(config.steps)) print("New index \(newIndex)") if scrollPosition != newIndex { withAnimation { scrollPosition = newIndex print("\(scrollPosition)") } } }) .onChange(of: scrollPosition, { oldIndex, newIndex in guard let pos = newIndex else { return } let newValue = CGFloat(pos) / CGFloat(config.steps) if abs(value - newValue) > 0.001 { value = newValue } }) } } private func horizontalTickMark(for index: Int) -> some View { let isMajorTick = index % config.steps == 0 let tickValue = index / config.steps return HStack(spacing: 8) { Rectangle() .fill(isMajorTick ? Color.accentColor : Color.gray.opacity(0.5)) .frame(width: isMajorTick ? 24 : 12, height: isMajorTick ? 2 : 1) if isMajorTick { Text("\(tickValue * 5)") .font(.system(size: 12, weight: .medium)) .foregroundColor(.primary) .fixedSize() } } .frame(maxWidth: .infinity, alignment: .trailing) .padding(.trailing, 8) } } #Preview("Vertical Scrubber") { struct VerticalScrubberPreview: View { @State private var value: CGFloat = 0 private let config = ScrubberConfig(count: 20, steps: 5, spacing: 8) var body: some View { VStack { Text("Vertical Scrubber (0–100 in steps of 5)") .font(.title2) .padding() HStack(spacing: 30) { VerticalScrubber(config: config, value: $value) .frame(width: 120, height: 300) .background(Color(.systemBackground)) .border(Color.gray.opacity(0.3)) VStack { Text("Current Value:") .font(.headline) Text("\(value * 5, specifier: "%.0f")") .font(.system(size: 36, weight: .bold)) .padding() HStack { Button("−5") { let newValue = max(0, value - 1) if value != newValue { value = newValue UISelectionFeedbackGenerator().selectionChanged() } print("Value \(newValue), \(value)") } .disabled(value <= 0) Button("+5") { let newValue = min(CGFloat(config.count), value + 1) if value != newValue { value = newValue UISelectionFeedbackGenerator().selectionChanged() } print("Value \(newValue), \(value)") } .disabled(value >= CGFloat(config.count)) } .buttonStyle(.bordered) } } Spacer() } .padding() } } return VerticalScrubberPreview() }
3
0
146
Jul ’25
.navigationTitle and List misbehaving with a Map()
When navigated to another view with a NavigationStack or NavigationView, the .navigationTitle modifying a List or Form containing a Map() gets quirky when trying to show the title. The back button is displayed correctly, but the title does not follow the same color scheme as the List of Form, rather it is white with a divider underneath it. It's like it is confusing the .inline with the .large navigation display modes. This doesn't just show up in the simulator, but on actual devices too. This is a test main view... import SwiftUI struct ContentView: View { var body: some View { NavigationStack { NavigationLink(destination: MapErrorView()) { Text("Map View") } } } } This is a test navigated view... import SwiftUI import MapKit struct MapErrorView: View { var body: some View { NavigationStack { Form { Section(header: Text("Map of the US States")) { Text("Map Error") Map() .frame(height: 220) } } .navigationTitle("Map Error") .navigationBarTitleDisplayMode(.large) } } } Attached is an image showing this error occurring. Does anyone know how I can get around this without using Text() to mock it? That might be the only way to get around this error.
3
0
126
Jul ’25
Shadow being drawn overtop stroke
I'm trying to have a RoundedRectangle with a slightly different color border (stroke in this case) with a shadow behind it. The issue I'm having is that the shadow itself is being drawn overtop the stroke. I've tried using a ZStack with another RoundedRectangle in the background with a shadow, but I kept running into the same issue. Anyone have any better ideas? Section { VStack { RoundedRectangle(cornerRadius: 11) .fill(color.shadow(.drop(color: .gray, radius: 2, x: 2, y: 2))) .stroke(color.opacity(0.5), lineWidth: 5) } .frame(height: 200) .padding() } .listRowInsets(EdgeInsets()) // Remove padding inside section, but causes clipping on the RoundedRectangle stroke .listRowBackground(Color.clear) // Remove background color
1
0
119
Jul ’25
App crashed when switching between Annotation Tab and Group Tab with TabView init(selection:content:)
This app will not crash when switching between these two tabs with TabView init(content:) import SwiftUI import SwiftData struct ContentView: View { @StateObject private var highlightManager = HighlightManager.shared @State private var selectedTab: Int = 0 var body: some View { TabView(selection: $selectedTab) { MapView() .tabItem { Label("Map", systemImage: "map") } .tag(0) // Annotation Tab AnnotationList() .tabItem { Label("Annotation", systemImage: "mappin.and.ellipse") } .tag(1) // Group Tab PeopleList() .tabItem { Label("Group", systemImage: "person.and.person") } .tag(2) } .tutorialOverlay() // Apply the overlay to the root view .environmentObject(highlightManager) .toolbar { ToolbarItem(placement: .confirmationAction) { NavigationLink("Help") { NavigationStack { HelpView(selectedTab: selectedTab) } } } } } }
1
0
61
Jul ’25
Xcode Crash on View Hierarchy debugger for mixed UIKit / SwiftUI app
For a large / older iOS app project, we have noticed the the view hierarchy debugger works fine for our UIKit screens, but runs into the following crasher whenever we try to launch the view hierarchy debugger on a UIHostingVC screen with SwiftUI content: Unable to capture the view hierarchy "AppName" encountered an unexpected error when processing the request for a view hierarchy snapshot. -- The operation couldn’t be completed. Log Title: Data source expression execution failure. Log Details: error evaluating expression “(BOOL)[[(Class)objc_getClass("DebugHierarchyTargetHub") sharedHub] performRequestInPlaceWithRequestInBase64:@"..."]”: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0x16b23bff8). Has anyone successfully resolved the underlying issue in this crasher? Tried all the typical recommendations for a clean build, clear derived data, use the "Debug -> View Debugging" menu - all with no resolution. Reported using Feedback Assistant: FB18514200 Thanks
1
0
133
Jul ’25
Incompatibility of matchedTransitionSource and sharedBackgroundVisibility
Take a look at following sample code. verify the shapes of two toolbar buttons. remove .matchedTransitionSource(id: 1, in: navigationNamespace) for one button. verify the toolbar button shape is changed to normal circle shape The combination usage of matchedTransitionSource and sharedBackgroundVisibility leads to unexpected display result. Removing any of these two view modifier restores the correct display. None of the view modifiers indicates it will crop the button shape. struct ContentView: View { @Namespace var navigationNamespace var body: some View { NavigationStack { ZStack { Color.gray } .ignoresSafeArea() .toolbar { ToolbarItem(placement: .topBarLeading) { Button { } label: { Image(systemName: "person") .font(.title3) .foregroundStyle(Color.accentColor) .frame(width: 50, height: 50) .glassEffect( .regular.interactive(), in: .circle ) } .matchedTransitionSource(id: 1, in: navigationNamespace) } .sharedBackgroundVisibility(.hidden) ToolbarItem(placement: .topBarTrailing) { Button { } label: { Image(systemName: "square.and.pencil") .font(.title3) .foregroundStyle(Color.accentColor) .frame(width: 50, height: 50) .glassEffect( .regular.interactive(), in: .circle ) } .matchedTransitionSource(id: 1, in: navigationNamespace) } .sharedBackgroundVisibility(.hidden) } } } } #Preview { ContentView() }
1
0
134
Jul ’25
How do I stop iPadOS from thinking a drag is for a new window?
On iPadOS 26, dragging my draggable() View near the edge of the screen is causing a new window to open. This doesn't happen with .onDrag on iPadOS 26, or with either .draggable() or .onDrag on iPadOS 18.5. This is not something I'm intending to offer in my app, and doesn't really make sense. Is there any way to prevent this from happening? Is this a bug? I couldn't find any new documentation. The thing being dragged: the "Font" rectangle on the right side of the screen, which represents an item in my app that is reorder-able when multiple are present.
1
1
68
Jul ’25
How can I avoid overlapping the new iPadOS 26 window controls without using .toolbar?
I'm building an iPad app targeting iPadOS 26 using SwiftUI. Previously, I added a custom button by overlaying it in the top-left corner: content .overlay(alignment: .topLeading) { Button("Action") { // ... } This worked until iPadOS 26 introduced new window controls (minimize/close) in that corner, which now overlap my button. In the WWDC Session Video https://developer.apple.com/videos/play/wwdc2025/208/?time=298, they show adapting via .toolbar, but using .toolbar forces me to embed my view in a NavigationStack, which I don’t want. I really only want to add this single button, without converting the whole view structure. Constraints: No use of .toolbar (as it compels a NavigationStack). Keep existing layout—just one overlayed button. Support automatic adjustment for the new window controls across all window positions and split-screen configurations. What I’m looking for: A way to detect or read the system′s new window control safe area or layout region dynamically on iPadOS 26. Use that to offset my custom button—without adopting .toolbar. Preferably SwiftUI-only, no heavy view hierarchy changes. Is there a recommended API or SwiftUI technique to obtain the new control’s safe area (similar to a custom safeAreaInset for window controls) so I can reposition my overlayed button accordingly—without converting to NavigationStack or using .toolbar?
2
4
277
Jul ’25
Tap area for focusing element during voice over is not correct
I have two overlay views on each side of a horizontal scroll. The overlay views are helper arrow buttons that can be used to scroll quickly. This issue occurs when I use either ZStack or .overlay modifier for layout. I am using accessibilitySortPriority modifier to maintain this reading order. Left Overlay View Horizontal Scroll Items Right Overlay View When voiceover is on and i do a single tap on views, the focus shifts to particular view as expected. But for the trailing overlay view, the focus does not shift to it as expected. Instead, the focus goes to the scroll item behind it.
0
0
26
Jul ’25
Tipkit for VisionOS (TabView, etc.)
I am trying to create a user flow where I can guide the user how to navigate through my app. I want to add a tip on a TabView that indicates user to navigate to a specific tab. I have seen this work with iOS properly but I am a little lost as VisionOS is not responding the same for .popoverTip etc. Any guidance is appreciated!
0
0
167
Jul ’25
Projecting a Cube with a Number in ARKit
I'm a novice in RealityKit and ARKit. I'm using ARKit in SwiftUI to show a cube with a number as shown below. import SwiftUI import RealityKit import ARKit struct ContentView : View { var body: some View { return ARViewContainer() } } #Preview { ContentView() } struct ARViewContainer: UIViewRepresentable { typealias UIViewType = ARView func makeUIView(context: UIViewRepresentableContext<ARViewContainer>) -> ARView { let arView = ARView(frame: .zero, cameraMode: .ar, automaticallyConfigureSession: true) arView.enableTapGesture() return arView } func updateUIView(_ uiView: ARView, context: UIViewRepresentableContext<ARViewContainer>) { } } extension ARView { func enableTapGesture() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:))) self.addGestureRecognizer(tapGestureRecognizer) } @objc func handleTap(recognizer: UITapGestureRecognizer) { let tapLocation = recognizer.location(in: self) // print("Tap location: \(tapLocation)") guard let rayResult = self.ray(through: tapLocation) else { return } let results = self.raycast(from: tapLocation, allowing: .estimatedPlane, alignment: .any) if let firstResult = results.first { let position = simd_make_float3(firstResult.worldTransform.columns.3) placeObject(at: position) } } func placeObject(at position: SIMD3<Float>) { let mesh = MeshResource.generateBox(size: 0.3) let material = SimpleMaterial(color: UIColor.systemRed, roughness: 0.3, isMetallic: true) let modelEntity = ModelEntity(mesh: mesh, materials: [material]) var unlitMaterial = UnlitMaterial() if let textureResource = generateTextResource(text: "1", textColor: UIColor.white) { unlitMaterial.color = .init(tint: .white, texture: .init(textureResource)) modelEntity.model?.materials = [unlitMaterial] let id = UUID().uuidString modelEntity.name = id modelEntity.transform.scale = [0.3, 0.1, 0.3] modelEntity.generateCollisionShapes(recursive: true) let anchorEntity = AnchorEntity(world: position) anchorEntity.addChild(modelEntity) self.scene.addAnchor(anchorEntity) } } func generateTextResource(text: String, textColor: UIColor) -> TextureResource? { if let image = text.image(withAttributes: [NSAttributedString.Key.foregroundColor: textColor], size: CGSize(width: 18, height: 18)), let cgImage = image.cgImage { let textureResource = try? TextureResource(image: cgImage, options: TextureResource.CreateOptions.init(semantic: nil)) return textureResource } return nil } } I tap the floor and get a cube with '1' as shown below. The background color of the cube is black, I guess. Where does this color come from and how can I change it into, say, red? Thanks.
4
0
104
Jul ’25
AppIntent perform function is not invoked from ControlWidget
I have an AppIntent that edits an object in my app. The intent accepts an app entity as a parameter, so if you run the intent it will ask which one do you want to edit, then you select one from the list and it shows a dialog that it was edited successfully. I use this same intent in my Home Screen widget initializing it with an objectEntity. The code needs to run in the app's process, not the widget extension process, so the file is added to both targets and it conforms to ForegroundContinuableIntent, and that is supposed to ensure it always runs in the app process. This works great when run from the Shortcuts app and when involved via a button in the Home Screen widget, exactly as expected. Here is that app intent: @available(iOS 17.0, *) struct EditObjectIntent: AppIntent { static let title: LocalizedStringResource = "Edit Object" @Parameter(title: "Object", requestValueDialog: "Which object do you want to edit?", inputConnectionBehavior: .connectToPreviousIntentResult) var objectEntity: ObjectEntity init() { print("INIT") } init(objectEntity: ObjectEntity) { self.objectEntity = objectEntity } @MainActor func perform() async throws -> some IntentResult & ReturnsValue<ObjectEntity> & ProvidesDialog { // Edit the object from objectEntity.id... return .result(value: objectEntity, dialog: "Done") } } @available(iOS 17.0, *) @available(iOSApplicationExtension, unavailable) extension EditObjectIntent: ForegroundContinuableIntent { } I now want to create a ControlButton that uses this intent: struct EditObjectControlWidget: ControlWidget { var body: some ControlWidgetConfiguration { StaticControlConfiguration(kind: "EditObjectControlWidget") { ControlWidgetButton(action: EditObjectIntent()) { Label("Edit Object", systemImage: "pencil") } } } } When I add the button to Control Center and tap it (on iOS 18), init is called 3x in the app process and 2x in the widget process, yet the perform function is not invoked in either process. No error appears in console logs for the app's process, but this appears for the widget process: LaunchServices: store <private> or url <private> was nil: Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=72, _LSFunction=_LSServer_GetServerStoreForConnectionWithCompletionHandler} Attempt to map database failed: permission was denied. This attempt will not be retried. Failed to initialize client context with error Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=72, _LSFunction=_LSServer_GetServerStoreForConnectionWithCompletionHandler} What am I doing wrong here? Thanks!
1
0
99
Jul ’25