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

SwiftUI Button fade animation happens with a delay when in ScrollView
When we place a Button inside a ScrollView , the fade animation of the button is delayed, so most users won't see it I think. You can see this in the trivial example struct ContentView: View { var body: some View { ScrollView { Button { // empty } label: { Text("Fade animation test") } } } } Is there any way to opt out of this behavior? In UIKit, this was also the default behavior, but you could always change it by overriding touchesShouldCancel method. I think I can probably do that by rewriting an animation completely with some custom ButtonStyle or by rewriting a Button component completely, but it doesn't seem like a good solution to me, as I want the native look and feel (in case of button animation it is pretty easy to mimic though). And also for some components, like lists, Apple has already implemented the correct behavior by themselves somehow.
3
0
94
Apr ’25
How to create a momentary segmented control in SwiftUI for macOS?
In AppKit, NSSegmentedControl has various styles defined by NSSegmentStyle and various tracking modes defined by NSSegmentSwitchTracking. How can we set these properties in SwiftUI? I'm currently using a Picker with the view modifier .pickerStyle(.segmented) applied but this seems to produce a segmented control with tracking set to "select one". In particular I'm looking for momentary tracking so that I can create navigation-style buttons for backward/forward navigation. Under AppKit, the canonical way to do this is an NSSegmentedControl of style separated and tracking momentary. Is that possible under SwiftUI for macOS? (Using the latest versions of everything.)
1
0
109
Apr ’25
Navigation
I am having trouble passing custom data in an array with a navigation stack. I want to display a subview with the same data structure (title, headline, picture placement etc), with different data attached for each of my list view items
0
0
53
Apr ’25
ObservableObjects get retained after a TextField is focused
When presenting a SwiftUI sheet containing ObservableObject's injected using environmentObject(_) modifier, the objects are unexpectedly retained after the sheet is dismissed if a TextField within the sheet gains focus or is edited. This issue occurs on iOS and iPadOS (on macOS the objects are always released), observable both in the simulator and on physical devices, and happens even when the view does not explicitly reference these environment objects, and the TextField's content isn't bound to them. Expected Results: When the sheet is dismissed, all environment objects passed to the sheet’s content view should be released (deinitialized), regardless of whether the TextField was focused or edited. Actual Results: If the TextField was focused or edited, environment objects (ObservableA and ObservableB) are retained after the sheet is dismissed. They are not deinitialized as expected, leading to unintended retention. Interestingly, previously retained copies of these environment objects, if any, are released precisely at the moment the TextField becomes focused on subsequent presentations, indicating an inconsistent lifecycle behavior. I have filed an issue FB17226970 Sample Code Below is a sample code that consistently shows the issue on iOS 18.3+. Steps to Reproduce: Run the attached SwiftUI sample. Tap the button labeled “Show Sheet” to present a sheet. Tap on the TextField to focus or begin editing. Dismiss the sheet by dragging it down or by other dismissal methods (e.g., tapping outside on iPadOS). import SwiftUI struct ContentView: View { @State private var showSheet: Bool = false var body: some View { VStack { Button("Show Sheet") { showSheet = true } } .sheet(isPresented: $showSheet) { SheetContentView() .environmentObject(ObservableA()) .environmentObject(ObservableB()) } } } struct SheetContentView: View { @State private var text: String = "" var body: some View { TextField("Select to retain observable objects", text: $text) .textFieldStyle(.roundedBorder) } } final class ObservableA: ObservableObject { init() { print(type(of: self), #function) } deinit { print(type(of: self), #function) } } final class ObservableB: ObservableObject { init() { print(type(of: self), #function) } deinit { print(type(of: self), #function) } } #Preview { ContentView() }
2
0
139
Apr ’25
unable to optimize App for iPad
I use swiftui to build apps on iPhone and iPad. There is no problem with the iPhone app. The game display is fully shown on iPhone. However, for the iPad, the game display is not shown and the screen goes black. I had to tap the button on the upper left side.(looks like a side view button) After that, the game display is only shown in the left side in a very small size. How can I make the game display fully shown in the iPad?
2
0
121
Apr ’25
Cursor display issue on attachment view in immersive space
While using Screen Mirroring in developer mode within my immersive space, I noticed an alignment issue with the computer cursor (transparent circle). When I move it toward an attachment view, the cursor remains horizontal instead of aligning with the surface of the attachment view. It shows correctly on a 2D window only wrong on attachment view. Is this behavior a bug, or could it be caused by a missing or incorrect configuration on the attachment view? Want help, thanks.
1
0
90
Apr ’25
Unable to use transitions for SwiftData in List
I can't for the life of me get transitions and animations to work well with SwiftData and List on MacOS 15 and iOS 18. I've included an example below, where I define several animations and a transition type, but they are all ignored. How do I animate items being added to / removed from a List()? I am attached to List() due to its support for selection, context menu, keyboard shortcuts, etc. If I would switch to ScrollView with VStack I would have to rebuild all of that. Also, this is super basic and should just work, right? Thanks for reading. import SwiftUI import SwiftData struct ContentView: View { @Environment(\.modelContext) private var modelContext /// Issues on iOS: /// Items animate into and out of view, but I seem to have no control over the animation. /// In the code here I've specified a 'bouncy' and a slow 'easeIn' animation: both are not triggered. /// The code also specifies using a 'slide' transition, but it is ignored. /// -> How do I control the transition and animation timing on iOS? /// /// Issues on MacOS: /// Items do not animate at all on MacOS! They instantly appear and are instantly removed. /// -> How do I control the transition and animation timing on MacOS? // animation added here -> has no effect? @Query(animation: .bouncy) private var items: [Item] var body: some View { VStack { Button("Add to list") { // called without 'withAnimation' -> no animation let newItem = Item(timestamp: Date()) modelContext.insert(newItem) } List() { ForEach(items, id: \.self) { item in Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard)) .transition(.slide) // items do not slide in/out of view .onTapGesture { // called with 'withAnimation' -> no animation withAnimation(.easeIn(duration: 2)) { modelContext.delete(item) } } } .animation(.spring(duration: 3), value: items) } } .padding() } } #Preview { ContentView() .modelContainer(for: Item.self, inMemory: true) }
5
1
1.5k
Apr ’25
Debug Failed in Xcode Simulator
I can‘t use breakpoints on the simulator after updating Xcode and the simulator. I can use breakpoints on a physical iPhone. I tired to download other iOS simulator version, but still not working. Both SwiftUI and UIKit not working. Xcode version: 16.2 SDK version: 18.2 (22C146) Simulator version: 18.3.1 (22D8075) Mac OS version: 15.4 Beta Couldn't find the Objective-C runtime library in loaded images. Message from debugger: The LLDB RPC server has crashed. You may need to manually terminate your process. The crash log is located in ~/Library/Logs/DiagnosticReports and has a prefix 'lldb-rpc-server'. Please file a bug and attach the most recent crash log.
49
63
15k
Apr ’25
drag a modelEntity inside an Immersive space and track position
Goal : Drag a sphere across the room and track it's position Problem: The gesture seems to have no effect on the sphere ModelEntity. I don't know how to properly attach the gesture to the ModelEntity. Any help is great. Thank you import SwiftUI import RealityKit import RealityKitContent import Foundation @main struct testApp: App { @State var immersionStyle:ImmersionStyle = .mixed var body: some Scene { ImmersiveSpace { ContentView() } .immersionStyle(selection: $immersionStyle, in: .mixed, .full, .progressive) } } struct ContentView: View { @State private var lastPosition: SIMD3<Float>? = nil @State var subscription: EventSubscription? @State private var isDragging: Bool = false var sphere: ModelEntity { let mesh = MeshResource.generateSphere(radius: 0.05) let material = SimpleMaterial(color: .blue, isMetallic: false) let entity = ModelEntity(mesh: mesh, materials: [material]) entity.generateCollisionShapes(recursive: true) return entity } var drag: some Gesture { DragGesture() .targetedToEntity(sphere) .onChanged { _ in self.isDragging = true } .onEnded { _ in self.isDragging = false } } var body: some View { Text("Hello, World!") RealityView { content in //1. Anchor Entity let anchor = AnchorEntity(world: SIMD3<Float>(0, 0, -1)) let ball = sphere //1.2 add component to ball ball.components.set(InputTargetComponent()) //2. add anchor to sphere anchor.addChild(ball) content.add(anchor) subscription = content.subscribe(to: SceneEvents.Update.self) { event in let currentPosition = ball.position(relativeTo: nil) if let last = lastPosition, last != currentPosition { print("Sphere moved from \(last) to \(currentPosition)") } lastPosition = currentPosition } } .gesture(drag) } }
0
0
60
Apr ’25
Inconsistent ornament scale
I am developing an application which make use of 2 ornaments anchored to a volumetric window, one used a toolbar and one to display different views. The problem I am facing consistently is that the ornaments seems to scale up or down after moving the volume using the OS handle or starting a GroupActivity session. This first image shows the ornaments as soon as I started the app, no dragging nor group activities: This second images shows them as soon as I join a group activity session: The map, which might seem smaller, has not been touched and has always the same scale. In this last image I had just dragged the entire volume using the OS toolbar, resulting in the ornaments scaling down: This is how the volume and the ornaments are declared: WindowGroup(id: "CityVolume") { let cityVM = CityViewModel(volumeSize: CityView.initialVolumeSize) CityView(cityVM: cityVM) .ornament(attachmentAnchor: .scene(.bottomFront)) { HStack { TourismChartsButton() LandmarksListButton() CenterMapButton() ToggleImmersiveSpaceButton() TrafficDataButton() BusLinesButton() } .padding() .offset(z: 10) .rotation3DEffect(Angle(degrees: 15), axis: (x: 1.0, y: 0.0, z: 0.0)) } .ornament(attachmentAnchor: .scene(.back)) { ZStack { if AppModel.Instance.tourismVM.isChartViewVisible { TourismChartsView() } if AppModel.Instance.busLinesVM.isDataViewEnabled { BusLineView() } } } .task(observeGroupActivity) .onAppear { appModel.cityVM = cityVM } } .windowStyle(.volumetric) .windowResizability(.contentSize) .volumeWorldAlignment(.gravityAligned) .defaultSize(CityView.initialVolumeSize, in: .meters) It happens also without starting a SharePlay session, but not as frequently as during SharePlay. Experienced the same behaviour with toolbars. Am I doing something wrong with how I created the ornaments? Am I missing something?
0
0
89
Apr ’25
Food Truck Sample animation issue from Table Component
Hi! I'm seeing some weird animation issues building the Food Truck sample application.^1 I'm running from macOS 15.4 and Xcode 16.3. I'm building the Food Truck application for macOS. I'm not focusing on iOS for now. The FoodTruckModel adds new Order values with an animation: // FoodTruckModel.swift withAnimation(.spring(response: 0.4, dampingFraction: 1)) { self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator)) } This then animates the OrdersTable when new Order values are added. Here is a small change to OrdersTable: // OrdersTable.swift - @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)] + @State private var sortOrder = [KeyPathComparator(\Order.creationDate, order: .reverse)] Running the app now inserts new Order values at the top. The problem is I seem to be seeing some weird animation issues here. It seems that as soon as the new Order comes in there is some kind of weird glitch where it appears as if part the animation is coming from the side instead of down from the top: What's then more weird is that if I seem to affect the state of the Table in any way then the next Order comes in with perfect animation. Scrolling the Table fixes the animation. Changing the creationData sort order from reverse to forward and back to reverse fixes the animation. Any ideas? Is there something about how the Food Truck product is built that would cause this to happen? Is this an underlying issue in the SwiftUI infra?
0
0
59
Apr ’25
Navbar buttons disappear in NavigationSplitView's sidebar when changing apps
We recently migrated our app to use NavigationSplitView on iPad with a sidebar and detail setup, and we got reports that the navigation buttons on the sidebar disappear when returning to our app after using a different app. I reproduced the issue from a new empty project with the following code (issue tested on iOS 17.4 and iOS 18.3, was not able to reproduce on iOS 16.4): import SwiftUI @main struct TestApp: App { var body: some Scene { WindowGroup { NavigationSplitView { Text("sidebar") .toolbar { ToolbarItem(placement: .topBarLeading) { Button(action: {}) { Image(systemName: "square.and.arrow.down") } } ToolbarItem(placement: .topBarTrailing) { Button(action: {}) { Image(systemName: "square.and.arrow.up") } } } } detail: { Text("detail") .toolbar { ToolbarItem(placement: .topBarLeading) { Button(action: {}) { Image(systemName: "eraser") } } ToolbarItem(placement: .topBarTrailing) { Button(action: {}) { Image(systemName: "pencil") } } } } } } } Please check the following GIF for the simple steps, notice how the navbar buttons in the detail view do not disappear: Here's the console output, it shows that the constraints break internally:
0
0
107
Apr ’25
Accessing an actor's isolated state from within a SwiftUI view
I'm trying to understand a design pattern for accessing the isolated state held in an actor type from within a SwiftUI view. Take this naive code: actor Model: ObservableObject { @Published var num: Int = 0 func updateNumber(_ newNum: Int) { self.num = newNum } } struct ContentView: View { @StateObject var model = Model() var body: some View { Text("\(model.num)") // <-- Compiler error: Actor-isolated property 'num' can not be referenced from the main actor Button("Update number") { Task.detached() { await model.updateNumber(1) } } } } Understandably I get the compiler error Actor-isolated property 'num' can not be referenced from the main actor when I try and access the isolated value. Yet I can't understand how to display this data in a view. I wonder if I need a ViewModel that observes the actor, and updates itself on the main thread, but get compile time error Actor-isolated property '$num' can not be referenced from a non-isolated context. class ViewModel: ObservableObject { let model: Model @Published var num: Int let cancellable: AnyCancellable init() { let model = Model() self.model = model self.num = 0 self.cancellable = model.$num // <-- compile time error `Actor-isolated property '$num' can not be referenced from a non-isolated context` .receive(on: DispatchQueue.main) .sink { self.num = $0 } } } Secondly, imagine if this code did compile, then I would get another error when clicking the button that the interface is not being updated on the main thread...again I'm not sure how to effect this from within the actor?
3
2
9.7k
Apr ’25
After updating to Xcode 16.3, getting the error - Symbol not found: ___cxa_current_primary_exception
It didn't happen with Xcode 16.2 that I used before, but after updating to 16.3, when I build the app, the following error is output to the console and the app doesn't run. dyld[2150]: Symbol not found: ___cxa_current_primary_exception Referenced from: <6B00A4F2-B208-3FDB-BA38-B7095AF0034A> /private/var/containers/Bundle/Application/B590DB18-9C66-4C9E-8330-104943419E60/Mubeat DEV.app/Mubeat DEV.debug.dylib Expected in: <7F51CB08-A0CA-386E-BB62-4B8BFB0CED9F> /usr/lib/libc++.1.dylib Symbol not found: ___cxa_current_primary_exception Referenced from: <6B00A4F2-B208-3FDB-BA38-B7095AF0034A> /private/var/containers/Bundle/Application/B590DB18-9C66-4C9E-8330-104943419E60/Mubeat DEV.app/Mubeat DEV.debug.dylib Expected in: <7F51CB08-A0CA-386E-BB62-4B8BFB0CED9F> /usr/lib/libc++.1.dylib dyld config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/usr/lib/libBacktraceRecording.dylib:/usr/lib/libMainThreadChecker.dylib:/usr/lib/libRPAC.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib After looking for another solution, I found a way to remove the -Objc option in Other Linker Flags, but this method only works on iOS 18.4 and doesn't work on other versions. Is there another solution?
5
4
2.1k
Apr ’25
Trying to drag a modelEntity inside an Immersive space
Goal : Drag a sphere across the room and track it's position Problem: The gesture seems to have no effect on the sphere ModelEntity. I don't know how to properly attach the gesture to the ModelEntity. Any help is great. Thank you import SwiftUI import Foundation import UIKit @main struct testApp: App { @State var immersionStyle:ImmersionStyle = .mixed var body: some Scene { ImmersiveSpace { ContentView() } .immersionStyle(selection: $immersionStyle, in: .mixed, .full, .progressive) } } struct ContentView: View { @State private var lastPosition: SIMD3? = nil @State var subscription: EventSubscription? @State private var isDragging: Bool = false var sphere: ModelEntity { let mesh = MeshResource.generateSphere(radius: 0.05) let material = SimpleMaterial(color: .blue, isMetallic: false) let entity = ModelEntity(mesh: mesh, materials: [material]) entity.generateCollisionShapes(recursive: true) return entity } var drag: some Gesture { DragGesture() .onChanged { _ in self.isDragging = true } .onEnded { _ in self.isDragging = false } } var body: some View { RealityView { content in //1. Anchor Entity let anchor = AnchorEntity(world: SIMD3<Float>(0, 0, -1)) let ball = sphere //2. add anchor to sphere anchor.addChild(ball) content.add(anchor) subscription = content.subscribe(to: SceneEvents.Update.self) { event in let currentPosition = ball.position(relativeTo: nil) if let last = lastPosition, last != currentPosition { print("Sphere moved from \(last) to \(currentPosition)") } lastPosition = currentPosition } } .gesture(drag) } }
1
0
63
Apr ’25
Is there a global Alert View in SwiftUI?
I am writing a SwiftUI based app, and errors can occur anywhere. I've got a function that logs the error. But it would be nice to be able to call an Alert Msg, no matter where I am, then gracefully exits the app. Sure I can right the alert into every view, but that seems ridiculously unnecessary. Am I missing something?
2
0
114
Apr ’25
TipViewStyle layout broken in iOS 18.4 – Tip message gets truncated
Hi everyone, I’m using a custom TipViewStyle to modify the background and slightly adjust the layout of the Tips in my app. Everything looked great until iOS 18.4. Since updating, the layout is being compressed, and the message inside the Tip is getting truncated. Here’s a screenshot of how it looks on iOS 18.4 (truncated message) and another showing how it used to look before iOS 18.4 (correct layout). Here is the relevant code for the custom style: struct CustomTipViewStyle: TipViewStyle { func makeBody(configuration: Configuration) -> some View { VStack(alignment: .leading, spacing: 4) { HStack { configuration.title? .font(.headline) .foregroundColor(.daBackground) Spacer() Button(action: { configuration.tip.invalidate(reason: .tipClosed) }) { Image(systemName: "xmark") .foregroundColor(.daBackground.opacity(0.3)) } } VStack(alignment: .leading, spacing: 8.0) { configuration.message? .font(.subheadline) .foregroundColor(.daBackground.opacity(0.8)) Divider().background(.daBackground.opacity(0.3)) ForEach(configuration.actions) { action in HStack { Spacer() Button(action: action.handler) { action.label() .foregroundStyle(.accent) .font(.system(size: 18, weight: .bold)) } } } } } .padding() .background(Color.daBlack) } } Has anyone else experienced this issue with TipViewStyle in iOS 18.4? Any workarounds or solutions would be appreciated! Thanks in advance!
1
1
106
Apr ’25
How do I maintain a stable scroll position when inserting items above in a ScrollView?
As the title says, I am not sure how to properly build an inverted ScrollView where I can safely insert items above my data ("prepend") without everything jumping around. My current code is essentially this: @State private var scrollPosition = ScrollPosition(idType: Message.ID.self) private func onMessageDidScrollIntoView(_ id: Message.ID) { let indexOfVisibleMessage = /* ... */ if indexOfVisibleMessage < 10 { fetchOlderMessages() // ^ this updates my ViewModel `messages` } } var body: some View { ScrollView { LazyVStack { ForEach(messages) { message in MessageCell(message) } }.scrollTargetLayout() } .defaultScrollAnchor(.bottom) .scrollPosition($scrollPosition) .onChange(of: scrollPosition) { oldValue, newValue in guard let visibleMessageId = scrollPosition.viewID(type: Message.ID.self) else { return } onMessageDidScrollIntoView(visibleMessageId) } } ..so if the user scrolls up to the oldest 10 messages, I start loading more and insert them at the top. The problem with this is that the ScrollView now jumps when new messages are inserted. This is because the ScrollView maintains it's Y position, but the content size changes since we are adding new items "above". I tried to play around with a few suggestions I found on StackOverflow, namely; Inverting the ScrollView (.scaleEffect(y: -1) on the ScrollView and then again on the MessageCell to counter it): This somehow jumped the x position of the ScrollView and completely breaks .contextMenu. Playing around with .onScrollGeometryChange to update scrollPosition.scrollTo(y:) when it's contentSize changes: This just didn't work and stopped the user scroll gesture/interaction. Setting scrollPosition to the Message.ID I want to keep stable before doing an update: This didn't do anything. But nothing actually worked for the reasons described above. How do you actually build these UIs in SwiftUI? I think an inverted ScrollView is quite a common UI, and obviously data has to be loaded lazily.
0
1
101
Apr ’25
Should i set window.isReleasedWhenClosed to true or leave it to default?
Hi, In mac os swift ui application when i set window.isReleasedWhenClosed and when i close the window the app is getting crashed with exc_bad_access. but when i leave it to default value the app is not crashing. for some windows setting window.isReleasedWhenClosed to true is woking properly when closing the windows. But for some windows it is crashing. If i dont set it to true the window is not removed from NSApplication.shared.windows sometimes. I am confused about setting isReleasedWhenClosed to true Could someone calrify on this please. thank in advance.
2
0
67
Apr ’25