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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Does LazyVStack and LazyVGrid release views from memory inside a ScrollView?
I am using LazyVStack inside a ScrollView. I understand that lazy views are rendered only when they come into view. However, I haven’t heard much about memory deallocation. I observed that in iOS 18 and later, when scrolling up, the bottom-most views are deallocated from memory, whereas in iOS 17, they are not (Example 1). Additionally, I noticed a similar behavior when switching views using a switch. When switching views by pressing a button, the view was intermittently deinitialized. (Example 2). Example 1) struct ContentView: View { var body: some View { ScrollView { LazyVStack { ForEach(0..<40) { index in CellView(index: index) } } } .padding() } } struct CellView: View { let index: Int @StateObject var viewModel = CellViewModel() var body: some View { Rectangle() .fill(Color.accentColor) .frame(width: 300, height: 300) .overlay { Text("\(index)") } .onAppear { viewModel.index = index } } } class CellViewModel: ObservableObject { @Published var index = 0 init() { print("init") } deinit { print("\(index) deinit") } } #Preview { ContentView() } Example 2 struct ContentView: View { @State var index = 0 var body: some View { LazyVStack { Button(action: { if index > 5 { index = 0 } else { index += 1 } }) { Text("plus index") } MidCellView(index: index) } .padding() } } struct MidCellView: View { let index: Int var body: some View { switch index { case 1: CellView(index: 1) case 2: CellView(index: 2) case 3: CellView(index: 3) case 4: CellView(index: 4) default: CellView(index: 0) } } } struct CellView: View { let index: Int @StateObject var viewModel = CellViewModel() var body: some View { Rectangle() .fill(Color.accentColor) .frame(width: 300, height: 300) .overlay { Text("\(index)") } .onAppear { viewModel.index = index } } } class CellViewModel: ObservableObject { @Published var index = 0 init() { print("init") } deinit { print("\(index) deinit") } } -------------------- init init init init init 2 deinit 3 deinit 4 deinit init
0
0
66
7h
SwiftUI: Major unannounced change in iOS18.4 beta1
Hi, I have noticed a major change to a SwiftUI API behavior in iOS18.4beta1 which breaks my app's functionality, and I've started hearing from users running the new beta that the app doesn't correctly work for them anymore. The problem is with views that contain a List with multiple-selection, and the contextMenu API applied with the ‘primaryAction’ callback that is triggered when the user taps on a row. Previously, if the user tapped on a row, this callback was triggered with the 'selectedItems' showing the tapped item. With iOS18.4beta, the same callback is triggered with ‘selectedItems’ being empty. I have the code to demonstrate the problem: struct ListSelectionTestView: View { @State private var items: [TimedItem] = [ TimedItem(number: 1, timestamp: "2024-11-20 10:00"), TimedItem(number: 2, timestamp: "2024-11-20 11:00"), TimedItem(number: 3, timestamp: "2024-11-20 12:00") ] @State var selectedItems = Set<TimedItem.ID>() var body: some View { NavigationStack { List(selection: $selectedItems) { ForEach(items) { item in Text("Item \(item.number) - \(item.timestamp)") } } .contextMenu(forSelectionType: TimedItem.ID.self, menu: {_ in Button(action: { print("button called - count = \(selectedItems.count)") }) { Label("Add Item", systemImage: "square.and.pencil") } }, primaryAction: {_ in print("primaryAction called - count = \(selectedItems.count)") }) } } } struct TimedItem: Identifiable { let id = UUID() let number: Int let timestamp: String } #Preview { ListSelectionTestView() } Running the same code on iOS18.2, and tapping on a row will print this to the console: primaryAction called - count = 1 Running the same code on iOS18.4 beta1, and tapping on a row will print this to the console: primaryAction called - count = 0 So users who were previously selecting an item from the row, and then seeing expected behavior with the selected item, will now suddenly tap on a row and see nothing. My app's functionality relies on the user selecting an item from a list to see another detailed view with the selected item's contents, and it doesn't work anymore. This is a major regression issue. Please confirm and let me know. I have filed a feedback: FB16593120
0
0
81
13h
Swift Charts: How to prevent scroll position jump when loading more data dynamically
I'm implementing infinite scrolling with Swift Charts where additional historical data loads when scrolling near the beginning of the dataset. However, when new data is loaded, the chart's scroll position jumps unexpectedly. Current behavior: Initially loads 10 data points, displaying the latest 5 When scrolling backwards with only 3 points remaining off-screen, triggers loading of 10 more historical points After loading, the scroll position jumps to the 3rd position of the new dataset instead of maintaining the current view Expected behavior: Scroll position should remain stable when new data is loaded User's current view should not change during data loading Here's my implementation logic using some mock data: import SwiftUI import Charts struct DataPoint: Identifiable { let id = UUID() let date: Date let value: Double } class ChartViewModel: ObservableObject { @Published var dataPoints: [DataPoint] = [] private var isLoading = false init() { loadMoreData() } func loadMoreData() { guard !isLoading else { return } isLoading = true let newData = self.generateDataPoints( endDate: self.dataPoints.first?.date ?? Date(), count: 10 ) self.dataPoints.insert(contentsOf: newData, at: 0) self.isLoading = false print("\(dataPoints.count) data points.") } private func generateDataPoints(endDate: Date, count: Int) -> [DataPoint] { var points: [DataPoint] = [] let calendar = Calendar.current for i in 0..<count { let date = calendar.date( byAdding: .day, value: -i, to: endDate ) ?? endDate let value = Double.random(in: 0...100) points.append(DataPoint(date: date, value: value)) } return points.sorted { $0.date < $1.date } } } struct ScrollableChart: View { @StateObject private var viewModel = ChartViewModel() @State private var scrollPosition: Date @State private var scrollDebounceTask: Task<Void, Never>? init() { self.scrollPosition = .now.addingTimeInterval(-4*24*3600) } var body: some View { Chart(viewModel.dataPoints) { point in BarMark( x: .value("Time", point.date, unit: .day), y: .value("Value", point.value) ) } .chartScrollableAxes(.horizontal) .chartXVisibleDomain(length: 5 * 24 * 3600) .chartScrollPosition(x: $scrollPosition) .chartXScale(domain: .automatic(includesZero: false)) .frame(height: 300) .onChange(of: scrollPosition) { oldPosition, newPosition in scrollDebounceTask?.cancel() scrollDebounceTask = Task { try? await Task.sleep(for: .milliseconds(300)) if !Task.isCancelled { checkAndLoadMoreData(currentPosition: newPosition) } } } } private func checkAndLoadMoreData(currentPosition: Date?) { guard let currentPosition, let earliestDataPoint = viewModel.dataPoints.first?.date else { return } let timeInterval = currentPosition.timeIntervalSince(earliestDataPoint) if timeInterval <= 3 * 24 * 3600 { viewModel.loadMoreData() } } } I attempted to compensate for this jump by adding: scrollPosition = scrollPosition.addingTimeInterval(10 * 24 * 3600) after viewModel.loadMoreData(). However, this caused the chart to jump in the opposite direction by 10 days, rather than maintaining the current position. What's the problem with my code and how to fix it?
0
0
77
20h
Searchable list with binding causes indexOutOfRange crash on iOS 18 physical device
Hi folks, Unsure if I've implemented some sort of anti-pattern here, but any help or feedback would be great. I've created a minimal reproducible sample below that lets you filter a list of people and mark individuals as a favourite. When invoking the search function on a physical device running iOS 18.3.1, it crashes with Swift/ContiguousArrayBuffer.swift:675: Fatal error: Index out of range. It runs fine on iOS 17 (physical device) and also on the various simulators I've tried (iOS 18.0, iOS 18.2, iOS 18.3.1). If I remove the toggle binding, the crash doesn't occur (but I also can't update the toggles in the view model). I'm expecting to be able to filter the list without a crash occurring and retain the ability to have the toggle switches update the view model. Sample code is below. Thanks for your time 🙏! import SwiftUI struct Person { let name: String var isFavorite = false } @MainActor class ViewModel: ObservableObject { private let originalPeople: [Person] = [ .init(name: "Holly"), .init(name: "Josh"), .init(name: "Rhonda"), .init(name: "Ted") ] @Published var filteredPeople: [Person] = [] @Published var searchText: String = "" { didSet { if searchText.isEmpty { filteredPeople = originalPeople } else { filteredPeople = originalPeople.filter { $0.name.lowercased().contains(searchText.lowercased()) } } } } init() { self.filteredPeople = originalPeople } } struct ContentView: View { @ObservedObject var viewModel = ViewModel() var body: some View { NavigationStack { List { ForEach($viewModel.filteredPeople, id: \.name) { person in VStack(alignment: .leading) { Text(person.wrappedValue.name) Toggle("Favorite", isOn: person.isFavorite) } } } .navigationTitle("Contacts") } .searchable(text: $viewModel.searchText) } } #Preview { ContentView() }```
2
0
73
23h
SwiftUI: Sheet presented from List row is not removed from screen when row is removed
I noticed if I show a sheet from a List row, then remove the row the sheet isn't removed from the screen like it is if using VStack or LazyVStack. I'd be interested to know the reason why the sheet isn't removed from the screen in the code below. It only occurs with List/Form. VStack/LazyVStack gives the expected result. I was wondering if it is an implementation issue, e.g. since List is backed by UICollectionView maybe the cells can't be the presenter of the sheet for some reason. Launch on iPhone 16 Pro Simulator iOS 18.2 Tap "Show Button" Tap "Show Sheet" What is expected: The sheet should disappear after 5 seconds. And I don't mean it should dismiss, I just mean removed from the screen. Similarly if the View that showed the sheet was re-added and its show @State was still true, then the sheet would be added back to the screen instantly without presentation animation. What actually happens: Sheet remains on screen despite the row that presented the sheet being removed. Xcode 16.2 iOS Simulator 18.2. struct ContentView: View { @State var showButton = false var body: some View { Button("\(showButton ? "Hide" : "Show" ) Button") { showButton = true Task { try? await Task.sleep(for: .seconds(5)) self.showButton = false } } //LazyVStack { // does not have this problem List { if showButton { SheetButton() } } } } struct SheetButton: View { @State var sheet = false @State var counter = 0 var body: some View { Text(counter, format: .number) Button("\(sheet ? "Hide" : "Show") Sheet") { counter += 1 sheet.toggle() } .sheet(isPresented: $sheet) { Text("Wait... This should auto-hide in 5 secs. Does not with List but does with LazyVStack.") Button("Hide") { sheet = false } .presentationDetents([.fraction(0.3)]) } // .onDisappear { sheet = false } // workaround } } I can work around the problem with .onDisappear { sheet = false } but I would prefer the behaviour to be consistent across the container controls.
0
0
142
1d
Simple console display test - preview not working as expected
Just learning Swift and SwiftUI, having fun in Xcode. I have the following custom view defined, but when I try to test it, the information doesn't get updated as I expect. When I use the button defined INSIDE the custom view, the update works as expected. When I use the button defined in the Preview body, it doesn't. The "lines" variable of the custom view appears not to be updated in that case. I know I'm missing something fundamental here about either view state binding or the preview environment, but I'm stumped. Any ideas? import SwiftUI struct ConsoleView: View { var maxLines : Int = 26 private enum someIDs { case textID} @State private var numLines : Int = 0 @State var lines = "a\nb\nc\n" var body: some View { VStack(alignment: .leading, spacing:0 ) { ScrollViewReader { proxy in ScrollView { Button("Scroll to Bottom") { withAnimation { proxy.scrollTo(someIDs.textID, anchor: .bottom) } } Text(lines) .id(someIDs.textID) .multilineTextAlignment(.leading) .frame(maxWidth: .infinity, alignment: .bottomLeading) .padding() .onChange ( of: lines) { withAnimation { proxy.scrollTo( someIDs.textID, anchor: .bottom) } } } Button("Add more") { writeln("More") //writeln(response) } } } } private func clipIfNeeded () { if (numLines>=maxLines) { if let i = lines.firstIndex(of: "\n") { lines = String(lines.suffix( from: lines.index(after:i))) } } } func writeln ( _ newText : String) { print("adding '\(newText)' to lines") //clipIfNeeded() write( newText ) write("\n") numLines += 1 print(lines) } func write ( _ newText : String) { lines += newText } } #Preview { VStack() { var myConsole = ConsoleView(lines: "x\ny\nz\n") myConsole Button("Add stuff") { myConsole.writeln("Stuff") } } }
2
0
136
1d
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
0
0
186
2d
.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
0
0
177
2d
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
138
2d
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
162
3d
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
121
3d
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
107
4d
@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
135
4d
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
153
4d
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
136
5d
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
257
5d
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
108
5d