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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

iOS App Crashes with SIGABRT and XCTest.framework Not Loaded (Xcode 16.2, SwiftUI 6)
Hello Apple Developer Community, I’m experiencing an issue with my iOS app, "WaterReminder," where it builds successfully in Xcode 16.2 but crashes immediately upon launch in the iPhone 16 Pro Simulator running iOS 18.3.1. The crash is accompanied by a "Thread 1: signal SIGABRT" error, and the Xcode console logs indicate a dyld error related to XCTest.framework/XCTest not being loaded. I’ve tried several troubleshooting steps, but the issue persists, and I’d appreciate any guidance or insights from the community. Here are the details: Environment: Xcode Version: 16.2 Simulator: iPhone 16 Pro, iOS 18.3.1 App: WaterReminder (written in SwiftUI 6) Build Configuration: Debug Issue Description: The app builds without errors, but when I run it in the iPhone 16 Pro Simulator, it shows a white screen and crashes with a SIGABRT signal. The Xcode debugger highlights the issue in the main function or app delegate, and the console logs show the following error: dyld[7358]: Library not loaded: @rpath/XCTest.framework/XCTest Referenced from: <549B4D71-6B6A-314B-86BE-95035926310E> /Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/WaterReminder.debug.dylib Reason: tried: '/Users/faytek/Library/Developer/Xcode/DerivedData/WaterReminder-cahqrulxghamvyclxaozotzrbsiz/Build/Products/Debug-iphonesimulator/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/Frameworks/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/Frameworks/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/Frameworks/XCTest.framework/XCTest' (no such file), '/Library/Developer/CoreSimulator/Volumes/iOS_22D8075/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.3.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/XCTest.framework/XCTest' (no such file) What I’ve Tried: ◦ Verified that FBSnapshotTestCase is correctly added to the "Embed Frameworks" build phase. ◦ Confirmed that the Framework Search Paths in build settings point to the correct location. ◦ Ensured that all required frameworks are available in the dependencies folder. ◦ Cleaned the build folder (Shift + Option + Command + K) and rebuilt the project. ◦ Checked the target configuration to ensure XCTest.framework isn’t incorrectly linked to the main app target (it’s only in test targets). ◦ Updated Xcode and the iOS Simulator to the latest versions. ◦ Reset the simulator content and settings. Despite these steps, the app continues to crash with the same dyld error and SIGABRT signal. I suspect there might be an issue with how XCTest.framework is being referenced or loaded in the simulator, possibly related to using SwiftUI 6, but I’m unsure how to resolve it. Could anyone provide advice on why XCTest.framework is being referenced in my main app (since it’s not intentionally linked there) or suggest additional troubleshooting steps? I’d also appreciate any known issues or workarounds specific to Xcode 16.2, iOS 18.3.1, and SwiftUI 6. Thank you in advance for your help! Best regards, Faycel
1
0
273
1w
.fileImporter not working on iPhone
I've been running into an issue using .fileImporter in SwiftUI already for a year. On iPhone simulator, Mac Catalyst and real iPad it works as expected, but when it comes to the test on a real iPhone, the picker just won't let you select files. It's not the permission issue, the sheet won't close at all and the callback isn't called. At the same time, if you use UIKits DocumentPickerViewController, everything starts working as expected, on Mac Catalyst/Simulator/iPad as well as on a real iPhone. Steps to reproduce: Create a new Xcode project using SwiftUI. Paste following code: import SwiftUI struct ContentView: View { @State var sShowing = false @State var uShowing = false @State var showAlert = false @State var alertText = "" var body: some View { VStack { VStack { Button("Test SWIFTUI") { sShowing = true } } .fileImporter(isPresented: $sShowing, allowedContentTypes: [.item]) {result in alertText = String(describing: result) showAlert = true } VStack { Button("Test UIKIT") { uShowing = true } } .sheet(isPresented: $uShowing) { DocumentPicker(contentTypes: [.item]) {url in alertText = String(describing: url) showAlert = true } } .padding(.top, 50) } .padding() .alert(isPresented: $showAlert) { Alert(title: Text("Result"), message: Text(alertText)) } } } DocumentPicker.swift: import SwiftUI import UniformTypeIdentifiers struct DocumentPicker: UIViewControllerRepresentable { let contentTypes: [UTType] let onPicked: (URL) -> Void func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIViewController(context: Context) -> UIDocumentPickerViewController { let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: contentTypes, asCopy: true) documentPicker.delegate = context.coordinator documentPicker.modalPresentationStyle = .formSheet return documentPicker } func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {} class Coordinator: NSObject, UIDocumentPickerDelegate { var parent: DocumentPicker init(_ parent: DocumentPicker) { self.parent = parent } func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { print("Success!", urls) guard let url = urls.first else { return } parent.onPicked(url) } func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { print("Picker was cancelled") } } } Run the project on Mac Catalyst to confirm it working. Try it out on a real iPhone. For some reason, I can't attach a video, so I can only show a screenshot
1
0
247
1w
LazyHstack in SwiftUI not supporting varying height views
In SwiftUI I want to create a list with LazyVstack and each row item in the LazyVstack is a LazyHstack of horizontally scrollable list of images with some description with line limit of 3 and width of every item is fixed to 100 but height of every item is variable as per description text content. But in any of the rows if the first item has image description of 1 line and the remaining items in the same row has image description of 3 lines then the LazyHStack is truncating all the image descriptions in the same row to one line making all the items in that row of same height. Why LazyHStack is not supporting items of varying height ? Expected behaviour should be that height of every LazyHStack should automatically adjust as per item content height. But it seems SwiftUI is not supporting LazyHstack with items of varying height. Will SwiftUI ever support this feature?
0
0
180
1w
Is it possible to automatically flip device orientation?
Hello togehter, i do have the following question. If I have my App run in landscape mode and a sheet view get's called, will it be possible to switch automatically from landscape mode in portrait mode and fix this device orientation? Once the sheet view get's dismissed or closed, the original view will come back and the device orientation shall switch back to landscape mode. Thanks you so much for your help!
0
0
198
1w
SwiftUI DatePicker
Hi, I found a behavioural difference in the DatePicker between WatchOS and iOS when limiting the date and time range. In the code below I'm attempting to limit the date and time range so that dates and times in past can be chosen. In iOS the DatePicker hides the dates and times that are out of range but WatchOS only the DatePicker for the date does this. The time DatePicker allows all times. The output from DatePicker is limited to the valid range, so it appears that it's the DatePicker UI that doesn't match the iOS behaviour. Does anyone know if there's a way to DatePicker that chooses the time only show valid times like iOS? import SwiftUI struct HistoryPeriodView: View { @State private var selectedDate = Date() @State private var selectedTime = Date() var body: some View { VStack { // Date Picker for selecting the date (Restricts to today or earlier) DatePicker("Select Date", selection: $selectedDate, in: ...Date.now, displayedComponents: [.date]) .labelsHidden() // Date Picker for selecting the time (Restricts to today or earlier) DatePicker("Select Time", selection: $selectedTime, in: ...Date.now, displayedComponents: [.hourAndMinute]) .labelsHidden() // Display selected Date & Time Text("\(formattedDateTime)") .font(.footnote) .padding() } } /// Formats the selected date and time for display private var formattedDateTime: String { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short return formatter.string(from: selectedTime) } } #Preview { HistoryPeriodView() }
2
0
169
1w
SwiftData crash when using a @Query on macOS 15.3.x
We use @Query macro in our App. After we got macOS 15.3 update, our App crashes at @Query line. SwiftData/Schema.swift:305: Fatal error: KeyPath \Item.<computed 0x0000000100599e54 (Vec3D)>.x points to a field (<computed 0x0000000100599e54 (Vec3D)>) that is unknown to Item and cannot be used. This problem occurs only when the build configuration is "Release", and only when I use @Query macro with sort: parameter. The App still works fine on macOS 14.7.3. This issue seems similar to what has already been reported in the forum. It looks like a regression on iOS 18.3. https://developer.apple.com/forums/thread/773308 Item.swift import Foundation import SwiftData public struct Vec3D { let x,y,z: Int } extension Vec3D: Codable { } @Model final class Item { var timestamp: Date var vec: Vec3D init(timestamp: Date) { self.timestamp = timestamp self.vec = Vec3D(x: 0, y: 0, z: 0) } } ContentView.Swift import SwiftUI import SwiftData struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query(sort: \Item.vec.x) // Crash private var items: [Item] var body: some View { NavigationSplitView { List { ForEach(items) { item in NavigationLink { Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))") } label: { Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard)) } } .onDelete(perform: deleteItems) } .navigationSplitViewColumnWidth(min: 180, ideal: 200) .toolbar { ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } } detail: { Text("Select an item") } } private func addItem() { withAnimation { let newItem = Item(timestamp: Date()) modelContext.insert(newItem) } } private func deleteItems(offsets: IndexSet) { withAnimation { for index in offsets { modelContext.delete(items[index]) } } } }
1
0
272
1w
@State memory leak Xcode 16.2
Hi, A class initialized as the initial value of an @State property is not released until the whole View disappears. Every subsequent instance deinitializes properly. Am I missing something, or is this a known issue? struct ContentView: View { // 1 - init first SimpleClass instance @State var simpleClass: SimpleClass? = SimpleClass(name: "First") var body: some View { VStack { Text("Hello, world!") } .task { try? await Task.sleep(for: .seconds(2)) // 2 - init second SimpleClass instance and set as new @State // "First" should deinit simpleClass = SimpleClass(name: "Second") // 3 - "Second" deinit just fine simpleClass = nil } } } class SimpleClass { let name: String init(name: String) { print("init: \(name)") self.name = name } deinit { print("deinit: \(name)") } } output: init: First init: Second deinit: Second Thanks
0
0
180
1w
XCode Launch Screen File wont save in project settings
Hey everyone! Totally a newbe question here but cant find the answer anywhere when searching so figured I would just post. Trying to create my first SwiftUI app in Xcode and wanted to create a simple launch screen with an image file, and a text label. however when I select the launch screen in the Project settings it lets me pick it, but then when i navigate away it never saves the value. Then when I go somewhere else and come back its blank again... Any thoughts? XCode 16.2
2
0
194
1w
App Launches on Login but Window Doesn't Appear Automatically (macOS Sequoia 15.2, Xcode 16.2)
I am developing a macOS app using SwiftUI, and I am encountering an issue when launching the app at login. The app starts as expected, but the window does not appear automatically. Instead, it remains in the Dock, and the user must manually click the app icon to make the window appear. Additionally, I noticed that the timestamp obtained during the app's initialization (init) differs from the timestamp obtained in .onAppear. This suggests that .onAppear does not trigger until the user interacts with the app. However, I want .onAppear to execute automatically upon login. Steps to Reproduce Build the app and add it to System Settings > General > Login Items as an item that opens at login. Quit the app and restart the Mac. Log in to macOS. Observe that the app starts and appears in the Dock but does not create a window. Click the app icon in the Dock, and only then does the window appear. Expected Behavior The window should be created and appear automatically upon login without requiring user interaction. .onAppear should execute immediately when the app starts at login. Observed Behavior The app launches and is present in the Dock, but the window does not appear. .onAppear does not execute until the user manually clicks the app icon. A discrepancy exists between the timestamps obtained in init and .onAppear. Sample Code Here is a minimal example that reproduces the issue: LoginTestApp.swift import SwiftUI @main struct LoginTestApp: App { @State var date2: Date init(){ date2 = Date() } var body: some Scene { WindowGroup { MainView(date2: $date2) } } } MainView.swift import SwiftUI struct MainView: View { @State var date1: Date? @Binding var date2: Date var body: some View { Text("This is MainView") Text("MainView created: \(date1?.description ?? "")") .onAppear { date1 = Date() } Text("App initialized: \(date2.description)") } } Test Environment Book Pro 13-inch, M1, 2020 macOS Sequoia 15.2 Xcode 16.2 Questions Is this expected behavior in macOS Sequoia 15.2? How can I ensure that .onAppear executes automatically upon login? Is there an alternative approach to ensure the window is displayed without user interaction?
0
0
176
1w
Is using to SwiftUI entry point and using NSViewControllerRepresentable to add NSViewController to hirarchy right approach ?
In macOS application, we are using SwiftUI as an entry point to our application and attaching appdelegate using NSApplicationDelegateAdaptor. We are using NSViewControllerRepresentable to add a View Controller to the hiracrchy so that we can store intance of viewcontroller and add content to it programatically . @main struct TWMainApp: App { @NSApplicationDelegateAdaptor private var appDelegate: TWAppDelegate internal var body : some Scene { TWInitialScene () } } TWInitialScene : public struct TWInitialScene : Scene { public var body : some Scene { WindowGroup { TWInitialView () } } } TWInitialView : struct TWInitialView : View { @Environment(\.scenePhase) private var scenePhase var body : some View { TWAppKitToSwiftUIBridge () } } TWAppKitToSwiftUIBridge : struct TWNSKitToSwiftUIBridge : NSViewControllerRepresentable { func makeNSViewController(context: Context) -> TWNSViewController { let view_hierarchy : TWNSViewController view_hierarchy = TWStaticContext.sViewController return view_hierarchy } func updateNSViewController(_ nsViewController: TWNSViewController, context: Context) { } } @objc public class TWStaticContext : NSObject { public static let sViewController = TWNSViewController () public override init () {} @objc public static func GetViewController () -> TWNSViewController { return TWStaticContext.sViewController } } public class TWNSViewController : NSViewController { override public func viewDidLoad () { super.viewDidLoad () } } To add content to the hirarchy we are accessing viewcontroller's intance and adding content to it like this : public func PaintInitialScreen () { let label = NSTextField(labelWithString: "TW window") label.frame = NSRect(x: 100, y: 200, width: 200, height: 200) // Adding content to viewcontroller TWStaticContext.sViewController.view.addSubview(label) } We are using this approach because we have a contraint in our application that we have to update UI programatically and on compile time we dont know what we want to show . We will be adding content on runtime based on how many button we want, what label we want , where to place it etc. When we were using purely appKit application, doing things programatically was simple but since SwiftUI is a declarative application we have to use above approach. Rational for shifting to SwiftUI entry point is that we want our application to be future safe and since apple is more inclined to SwiffUI, we want to design our entry flow to use SwiftUI entry point . And SwiftUI being declarative, we are using appKit to add content to hiracrchy programtically. We have used similar apprach in iOS also , where are using UIApplicationDelegateAdaptor inplace of NSApplicationAdaptor . And UIViewControllerReprestable in place of NSViewControllerRepresentable. Is this right approach to use ?
1
0
311
1w
Optimal Way of Getting Screen Resolution Using SwiftUI
Hi all, I am looking for a futureproof way of getting the Screen Resolution of my display device using SwiftUI in MacOS. I understand that it can't really be done to the fullest extent, meaning that the closest API we have is the GeometeryProxy and that would only result in the resolution of the parent view, which in the MacOS case would not give us the display's screen resolution. The only viable option I am left with is NSScreen.frame. However, my issue here is that it seems like Apple is moving towards SwiftUI aggressively, and in order to futureproof my application I need to not rely on AppKit methods as much. Hence, my question: Is there a way to get the Screen Resolution of a Display using SwiftUI that Apple itself recommends? If not, then can I rely safely on NSScreen's frame API?
2
0
185
1w
Removing Grid Lines from Charts in SwiftUI
Hi, I have created a line graph using LineMark in Charts, which by default includes grid lines and axes lines. My requirement is to remove the grid lines but retain the axes lines and the values. I have tried the following code: .chartXAxis { AxisMarks(preset: .extended, values: .stride(by: 2), stroke: StrokeStyle(lineWidth: 0)) } This is removing grid lines as well as axes lines. How to retain axes lines while removing grid lines ?
2
0
208
1w
high internal cpu usage
Hi, I am developing a new SwiftUI app. Running under OSX, I see very high cpu usage (I am generating lots of gpu based updates which shouldn't affect the cpu). I have used the profiler to ensure my swift property updates are minimal, yet the cpu usage is high coming from SwiftUI. It seems the high cpu usage is coming from NSAppearance, specifically, CUICopyMeasurements - for a single button??? But the swift updates don't show any buttons being updating
0
0
190
1w
Swiftui Charts
I have a SwiftUI LineMark chart that inverts the y axis when the data the chart is plotting is all zeros. I'm expecting the y axis 0 to be at the bottom but when the data is all zeros it's at the top. Below is an example demonstrating the problem: import SwiftUI import Charts struct ChartView: View { let data: [Double] = [0,0,0,0,0] var body: some View { Chart { ForEach(data.indices, id: \.self) { index in LineMark( x: .value("Index", index), y: .value("Value", data[index]) ) } } .chartYAxis { AxisMarks(values: [0, 10, 20, 30, 40, 50]) { value in AxisValueLabel() AxisTick() AxisGridLine() } } .padding() } } I can't use .chartYScale(domain: ) because it overrides the chartYAxis where the real code creates custom a leading and trailing y axis. Does anyone have any suggestions how I may fix this?
5
0
329
1w
How to post openWindow, closeSpecificWindow, hideSpecificWindow from a swift class?
I am considering of shifting my codebase from appkit to SwiftUI entry point. In Appkit, we get control on each NSWindow. So that we can hide/resize window, close window and controll when to present a specific window . Because i have access to NSWindow instance which i can store and perform these actions. But when i shift to SwiftUI entry point, i declare struct conforming to SwiftUI Scene. And new windows will be created with the instance of this scene. I am using NSViewControllerRepresentable to add a NSViewController to the hierarchy of these scene. And adding content to this NSViewController's instance to show on screen. I need help in controlling the size of these windows. How can i close specific window ? Resize specific window ? or Hide specific window? If i use purely SwiftUI view's , then i can do this by using the Enviorment propery and use DismissWindow to close a window or openWindow with identifier to open a specific window by passing the specificer . But i am using Appkit's NSViewController where i will add buttons in heirarchy from which i want to trigger these events . And in that case how can i controll a specific window in case of multiwindow application?
2
0
194
1w
Closure with typed throws stored as a View property crashes on iOS 17
I've encountered an issue where storing a throws(PermissionError) closure as a property inside a SwiftUI View causes a runtime crash on iOS 17, while it works correctly on iOS 18. Here’s an example of the affected code: enum PermissionError: Error { case denied } struct PermissionCheckedView<AllowedContent: View, DeniedContent: View>: View { var protectedView: () throws(PermissionError) -> AllowedContent var deniedView: (PermissionError) -> DeniedContent init( @ViewBuilder protectedView: @escaping () throws(PermissionError) -> AllowedContent, @ViewBuilder deniedView: @escaping (PermissionError) -> DeniedContent ) { self.protectedView = protectedView self.deniedView = deniedView } public var body: some View { switch Result(catching: protectedView) { case .success(let content): content case .failure(let error): deniedView(error) } } } @main struct TestApp: App { var body: some Scene { WindowGroup { PermissionCheckedView { } deniedView: { _ in } } } } Specifically this is the stack trace (sorry for the picture I didn't know how to get the txt): If I use var protectedView: () throws -> AllowedContent without typed throws it works.
2
0
200
1w
Multiple issues with SwiftUI TabView in sidebarAdaptable mode
We are trying to write an iOS app that supports regular and constrained widths using a TabView with .tabViewStyle(.sidebarAdaptable). On the surface this seems like a great way to write an app that supports all the different widths that your app may run in. Especially since Stage Manager and Apple Vision have made it easy for users to resize your apps window while it is running. We are facing many challenges though. I will give a brief one liner of each below, but to truly experience them you need to run the sample app, or watch the sample videos included. Issues Basic TabView Issues Double Navigation Bar: When tabs are collapsed into a "More" tab, there's an unwanted double navigation bar Selection Sync: Tab selection gets out of sync when switching between narrow/wide layouts through the "More" tab TabView Crash Fatal crash occurs when resizing window to narrow width while Tab 5 is selected Error: SwiftUI/SidebarAdaptableTabViewStyle_iOS.swift:482: Fatal error: Tried to update with invalid selection value Section Handling Issues Section Display Bug: Bottom tabs incorrectly show section names instead of tab names in narrow width Tab Selection Mismatch: Tab identifiers don't match selected tabs in narrow width mode Customization Issues Inconsistent "Edit" button behavior in More tab Unable to properly disable tab customization Sample app and video https://github.com/copia-wealth-studios/swiftui-tabview-sample
1
1
253
1w