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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Availablility check is incorrect on visionOS
With this sample code here: import SwiftUI struct ContentView: View { var body: some View { Text("Hello world") .hoverEffect(isEnabled: true) } } private extension View { func hoverEffect(isEnabled: Bool) -> some View { if #available(iOS 17.0, *) { // VisionOS 2.0 goes in here? return self .hoverEffect(.automatic, isEnabled: isEnabled) } else { return self } } } You would expect if the destination was visionOS it would go into the else block but it doesn't. That seems incorrect since the condition should be true if the platform is iOS 17.0+. Also, I had this similar code that was distriubted via a xcframework and when that view is used in an app that is using the xcframework while running against visionOS there would be a runtime crash (EXC_BAD_ACCESS). The crash could only be reproduced when using that view from the xcframework and not the local source code. The problem was fixed by adding visionOS 1.0 to that availability check. But this shouldn't have been a crash in the first place. Does anyone have thoughts on this or possibly an explanation? Thank you!
4
2
120
10h
SwiftUI DatePicker UI doesn't match the actual data
I have a view for editing time information。The view has two properties startTime and endTime wrapped using @binding, of type Date? @Binding var startTime: Date? @Binding var endTime: Date? Different components are displayed depending on whether they have a value or not, the logic is the same for both. if startTime == nil { // something } else { DatePicker("Start Time", selection: Binding( get: { startTime! }, set: { startTime = $0 } )) } if endTime == nil { // something } else { DatePicker("End Time", selection: Binding( get: { endTime! }, set: { endTime = $0 } )) } Execute the initData method when the view appears. private func initData() { print("Start Time: \(String(describing: startTime))") print("End Time: \(String(describing: endTime))") } The output of the open view is as follows: Start Time: Optional(2024-10-11 08:07:35 +0000) End Time: Optional(2024-10-11 08:08:35 +0000) Screenshot of the interface display: The end time is displayed correctly in the view that opens, and the start time shows the current time. The data seen via DEBUG is consistent with the console output, there is just a problem with the display. I don't make any changes and just click the save button and the data is still ‘2024-10-11 08:07:35 +0000’. I hope to get some answers, thanks!
0
0
44
17h
Badge signature has changed in iOS 18
Hi, I'm trying to add a badge to a Tab when a certain condition is met. Prior to iOS 18 I could do .badge(showBadge ? "Show" : nil). However, in iOS 18 I'm getting the following error message 'nil' cannot be used in context expecting type 'LocalizedStringKey'. Right clicking the .badge -> Jump to Definition shows the following /// Generates a badge for the tab from a localized string key. /// /// Use a badge to convey optional, supplementary information about a /// view. Keep the contents of the badge as short as possible. The string /// provided will appear as an indicator on the given tab. /// /// This modifier creates a ``Text`` view on your behalf, and treats the /// localized key similar to ``Text/init(_:tableName:bundle:comment:)``. For /// more information about localizing strings, see ``Text``. The /// following example shows a tab that has a "New Alerts" badge /// when there are new alerts. /// /// var body: some View { /// TabView { /// Tab("Home", systemImage: "house") { /// HomeView() /// } /// Tab("Alerts", systemImage: "bell") { /// AlertsView() /// } /// .badge(alertsManager.hasAlerts ? "New Alerts" : nil) /// } /// } /// /// - Parameter key: A string key to display as a badge. nonisolated public func badge(_ key: LocalizedStringKey) -> some TabContent<Self.TabValue> Here it looks like that the signature of .badge has changed to a non-nil LocalizedStringKey from pre-iOS 18 LocalizedStringKey?. Any ideas how to solve this?
1
0
51
17h
modelContext.save triggers warning: publishing changes from background threads is not allowed
I am seeing a strange warning pop up in my SwiftData ModelActor: Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates. This warning is triggered by the try self.modelContext.save() call in the following function in my ModelActor: public func purgeLocalEvents(for calendarId: PersistentIdentifier) async { do { let calendars = try self.modelContext.fetch(CalendarFetchDescriptors.getCalendar(calendarId)) if let calendar = calendars.first { if let events = calendar.events { for event in events { self.modelContext.delete(event) } } calendar.lastSync = .distantPast try self.modelContext.save() } } catch { debugPrint("Error loading calendar for event purge", error.localizedDescription) } } The function in the ModelActor is called like this: Task.detached(priority: .userInitiated) { let actor = await RemoteGoogleCalendarActor(modelContainer: SwiftDataCoordinator.shared.fullContainer) await actor.purgeLocalEvents(for: calendarId) } I perform saves from modelactors in many other places, and I've never seen this warning before. What could be causing this issue?
1
0
41
19h
NavigationStack in TabView not working as expected
Hi all! I encountered some strange behaviour that I cannot explain. When I have a NavigationStack that is embedded in a TabView, and that NavigationStack uses a NavigationPath that is stored within an ObservableObject, and the view within the NavigationStack gets its NavigationDestinations via an extension on the View object (either via a direct function or via a ViewExtension), the navigation doesn't work as expected, namely that back button seems to not pop views from the path. Consider the following example: struct ContentView: View { var body: some View { TabView { NavViewContainer1() .tabItem { Text("One") } NavViewContainer2() .tabItem { Text("Two") } } } } @MainActor class Model: ObservableObject { @Published var path = NavigationPath() } struct NavViewContainer1: View { @StateObject private var model = Model() var body: some View { NavigationStack(path: $model.path) { VStack { Text("1").font(.title).padding() NavigationLink(value: "One") { Text("Dest 1") } NavigationLink(value: "Two") { Text("Dest 2") } } .navigationDestination(for: String.self) { Text($0) } } } } struct NavViewContainer2: View { @StateObject private var model = Model() var body: some View { NavigationStack(path: $model.path) { VStack { Text("2").font(.title).padding() NavigationLink(value: "One") { Text("Dest 1") } NavigationLink(value: "Two") { Text("Dest 2") } } .setUpDestinations() } } } extension View { func setUpDestinations() -> some View { navigationDestination(for: String.self) { Text($0) } } } When clicking the destination buttons on the first tab (so in NavViewContainer1, I can go to a child view, back to the root, then click the other link to go to a child view and back to the root, all good. The route taken looks like this: Root > Dest 1 > Root > Dest 2 > Root. However, when I do the same in the second tab (NavViewContainer2), as soon as I click on the second destination, it seems like the first destination was not removed from the path, since clicking the back button in the second destination brings me to the first destination. The route taken looks like this: Root > Dest 1 > Root > Dest 2 > Dest 1 > Root. If I either move the view out of the TabView, move the path inside of the view with a @State variable or as in view 1 add the navigationDestinations directly, the path works as expected. Only the combination of TabView + NavigationPath in ObservableObject + view extension yields this behaviour. Am I missing something here, or is this a bug in the SwiftUI framework?
0
0
29
19h
SwiftUI Scroll Issue with Keyboard Type Change
Hello, I'm developing with SwiftUI and have encountered some bug-like behavior that I haven't been able to resolve, so I'm seeking your assistance. I'm building my view using TextEditor, ScrollViewReader, and List, and I've noticed a strange behavior. When the TextEditor at the bottom of the view is focused and the keyboard is displayed, if I change the keyboard type to Emoji and then switch back to the language keyboard, the scroll becomes misaligned. Although the TextEditor remains focused, when this bug occurs, the view's offset is reset as if the focus was lost. Could you help me with this?
0
0
56
1d
MapCameraPosition camera region rect item all of them are nil
@State var position : MapCameraPosition = .userLocation(fallback: .region(.defaultRegion)) Map(position: $position) {} .onAppear { Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in print("check.position",position.camera,position.region,position.rect,position.item) } } All of the value are nil, so how do I get the current camera position?? check.position nil nil nil nil check.position nil nil nil nil check.position nil nil nil nil check.position nil nil nil nil check.position nil nil nil nil check.position nil nil nil nil check.position nil nil nil nil check.position nil nil nil nil It is always nil (even if I manually move around the Map with a finger)
1
0
66
1d
SwiftData iCloud sync breaks after disabling and re-enabling iCloud
A fairly simple ModelContainer: var sharedModelContainer: ModelContainer = { let schema = Schema([ Model1.self, Model2.self, Model3.self ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false, cloudKitDatabase: .automatic) do { let container = try ModelContainer(for: schema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) return container } catch { fatalError("Error: Could not create ModelContainer: \(error)") } }() After upgrading to macOS 15 and disabling/enabling iCloud for the app the sync stopped working on Mac. The steps: Go to System Settings > Apple Account > iCloud > Saved to iCloud > See all find the App and disable iCloud. After this synced items are removed from the app and some errors thrown in the console ('..unable to initialize without an iCloud account...') Re-enable the iCloud setting This error appears in the console: CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate resetAfterError:andKeepContainer:](612): <NSCloudKitMirroringDelegate: 0x6000020dc1e0> - resetting internal state after error: Error Domain=NSCocoaErrorDomain Code=134415 "(null)" On macOS Sonoma the items are synced back to the app and the sync is restored, but on Sequoia they don't come back and the sync is not working. I tried resetting the container, deleting all data - no help. Submitted FB15455847
2
0
101
1d
Using Generic SwiftData Modules
Hi, I have the view below that I want it to get any sort of SwiftData model and display and string property of that module, but I get the error mentioned below as well, also the preview have an error as below, how to fix it ? I know its little complicated. Error for the view GWidget " 'init(wrappedValue:)' is unavailable: The wrapped value must be an object that conforms to Observable " Error of preview " Cannot use explicit 'return' statement in the body of result builder 'ViewBuilder' " 3, Code #Preview { do { let configuration = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: Patient.self, configurations: configuration) let example = Patient(firstName: "Ammar S. Mitoori", mobileNumber: "+974 5515 7818", homePhone: "+974 5515 7818", email: "ammar.s.mitoori@gmail.com", bloodType: "O+") // Pass the model (Patient) and the keyPath to the bloodType property return GWidget(model: example, keyPath: \Patient.bloodType) .modelContainer(container) } catch { fatalError("Fatal Error") } } 4. Code for the Gwidget View ```import SwiftUI import SwiftData struct GWidget<T>: View { @Bindable var model: T var keyPath: KeyPath<T, String> // Key path to any string property // Variables for the modified string and the last character var bloodTypeWithoutLast: String { let bloodType = model[keyPath: keyPath] return String(bloodType.dropLast()) } var lastCharacter: String { let bloodType = model[keyPath: keyPath] return String(bloodType.suffix(1)) } var body: some View { VStack(alignment: .leading) { Text("Blood Type") .font(.footnote) .foregroundStyle(sysPrimery07) HStack (alignment: .lastTextBaseline) { Text(bloodTypeWithoutLast) .fontWeight(.bold) .font(.title2) .foregroundStyle(sysPrimery07) VStack(alignment: .leading, spacing: -5) { Text(lastCharacter) .fontWeight(.bold) Text(lastCharacter == "+" ? "Positive" : "Negative") } .font(.caption2) .foregroundStyle(lastCharacter == "+" ? .green : .pink) } } } }
0
0
71
1d
TabView with TabSection crashing on iPad
We have an iPad app and are using the new TabView and TabSection views in our sidebar. The TabSection is populated with data from a @FetchRequest that fetches data from CoreData. The data in CoreData is updated by a single worker that makes sure every value only exists once. This is done by using an OperationQueue with maxConcurrentOperationCount set to 1. This is crashing for our users, and we can't figure out why. We can't reproduce it, and it only seems to happen on iPadOS. We have the same code running on macOS and haven't received any reports. (We collect them all via 3rd party). The error is: NSInternalInconsistencyException Fatal: supplied item identifiers are not unique. Duplicate identifiers: {( ... )} Where ... is one to many comma separated strings. In our latest update we made sure the values are unique by passing them through a Set, unfortunately this is till crashing. Here's the fix we tried. var uniqueTags: [HashTag] { let set = Set(hashTags) let array = Array(set) return array.sorted { $0.name?.lowercased() ?? "" < $1.name?.lowercased() ?? "" } } We're out of ideas and have no idea what to do next.
2
1
124
1d
How can I use an image for my live activity smartstack layout?
Hello, I am updating my live activity for the new ios18 Smart Stack functionality. I got it working through the WWDC session (Bring your live activities to Apple watch). I'm doing supplementalActivityFamilies([.small]) and then a custom layout in the .small ActivityFamily However, any images I try to use in the Smart Stack just show up as grey squares. (it works on the phone live activity) I suspect it's because my app images are not moved over to the watch? Because I don't have a watch app and such no watch target? If anyone can help me understand if there's anything I can do in order to have a custom image show up on the smart stack, I'd be very grateful.
3
0
66
1d
WidgetKit widgets vanish in Montery with Xcode 16
We have recently added WidgetKit widgets to an existing product, and they've been working great on Macs using Big Sur and later. Recently, when installing a build on a Montery Mac, the widgets were no longer in Notification Center. After some trial and error, we discovered that if we build the project with Xcode 15.4, the widgets appear, but if we build with Xcode 16, the widgets vanish. This seems to happen on Macs running Big Sur or Monterey. The project is being built on Macs running Sonoma (both Apple Silicon and Intel). Is there a build setting in Xcode 16 that may have this effect?
0
1
78
2d
Hand Gesture Controls in an Apple Watch App
Hello everyone! I want to add hand gesture controls to my Apple Watch app. Specifically, I’m looking to implement the following gestures: 1. Tapping index finger and thumb together once 2. Tapping index finger and thumb together twice 3. Fist clench 4. Double fist clench Each gesture should trigger a different action within the app. However, I can’t find any information on how to implement this. I only came across an example using .handGestureShortcut(.primaryAction) (Enabling the double-tap gesture on Apple Watch https://developer.apple.com/documentation/watchOS-Apps/enabling-double-tap), but I need to handle four distinct gestures. Is this possible in watchOS 11? Any guidance or examples would be greatly appreciated! Thank you!
1
0
82
2d
Issue: Device Dock pops up on switching the app to or from Single App mode
I have an issue while unlocking the app from Single App mode. Device Dock is popping up on top of my app and this is disturbing the experience of my app. I have already done MDM configuration and the indented functionality is working fine with the below code, the app is successfully switching to single app mode and back. The sample code below reproduces the issue. Tap on Lock, the completion blocks returns true and the app is successfully switched to single app mode. Tap on Unlock, the completion block returns true and the app is successfully switched from the single app mode. Now the device dock is popped up on top of the app. struct LockApp: App { var body: some Scene { WindowGroup { VStack { Button("Lock", systemImage: "lock") { UIAccessibility.requestGuidedAccessSession(enabled: true) { success in print("App has been locked", success) } } .buttonStyle(.borderedProminent) Button("UnLock", systemImage: "lock.open") { UIAccessibility.requestGuidedAccessSession(enabled: false) { success in print("App has been unlocked", success) } } .buttonStyle(.borderedProminent) } } } } Xcode Version: 16.0 Device: iPad Pro 12.9 inch 6th gen. OS: 18.1 Is this intended behaviour? Has anyone come across this issue?
0
0
44
2d
Focus fails when TextField includes axis: .vertical
I've found another interesting issue with the Focus system. My text case is SwiftUI in Preview or Simulator (using an iPad mini case) -- I haven't tried this on other environments, so your mileage may vary. I have a Form including several TextFields. Adding the usual @FocusState logic, I observe that if I type a TAB key, then (a) If the TextFields are specified using TextField(“label”, text: $text), typing the tab key switches focus from field to field as expected, BUT (b) If the TextFields are specified using TextField(“label”, text: $text, axis: .vertical), typing the tab key adds whitespace to the field and does NOT change focus. In the latter case, I need to use an .onKeyPress(.tab) {….} modifier to achieve the desired result. Reported as FB15432840
0
0
90
3d
StateObject isn't being deallocated whilst it's containing View has disappeared
Hi! Seems StateObject isn't being deallocated whilst it's containing View has disappeared successfully. Suppose overlay is the cause. StateObject hangs until next view body evaluation happens. import SwiftUI final class Copmanion: ObservableObject { deinit { print("☠️ Copmanion died") } } @MainActor final class SessionManager: ObservableObject { @Published var isActive = false } struct CheckPasscodeView: View { @EnvironmentObject var session: SessionManager @StateObject var copmanion = Copmanion() var body: some View { VStack { Button("Login") { session.isActive = true } } .onAppear { print("CheckPasscodeView appear") } .onDisappear { print("CheckPasscodeView disappear") } } } struct ContentView: View { @StateObject var session = SessionManager() var body: some View { Color.teal .overlay { if !session.isActive { CheckPasscodeView() .environmentObject(session) } else { EmptyView() } } } } ZStack here is one of possible solutions as well as using Observation framework. Conditions: Xcode 16 Xcode 16.1 Beta 2 iphoneosSDK 18.1
1
0
72
3d
preferredColorScheme not working with Xcode 16
In this app, I set the preferredColorScheme in main @main struct TheApp: App { @AppStorage("isDarkMode") private var isDarkMode = false var body: some Scene { WindowGroup { ContentView() .preferredColorScheme(isDarkMode ? .dark : .light) } } } isDarkMode is changed dynamically in code. When code is compiled with Xcode 15.3, the background of ContentView changes from light to dark or vice versa. When compiled with Xcode 16, no more change. However, direct changes to objects do work, such as: TextField("N", value: $t, format: .number) .frame(width: 40) .background(isDarkMode ? .gray : .white) What has changed in Xcode 16 ? Is it documented somewhere ? I saw this SO thread which describe similar problem. https://www.reddit.com/r/swift/comments/upkprg/preferredcolorscheme_toggle_not_working/
10
0
189
3d
Xcode 16.0 + SwiftUI: Failed to launch app "MyApp.app" in reasonable time
I am working on transitioning an existing UIKit based app to SwiftUI. After adding a first SwiftUI file to the project preview fails with: Failed to launch app "MyApp.app" in reasonable time The View code is the default templates, thus definitly not too complex: import SwiftUI struct OverviewPageView: View { var body: some View { Text("Hello, World!") } } #Preview { OverviewPageView() } Things I have tried: Cleaning and rebuilding. Changing the target device. Using xcrun simctl shutdown all followed by scrub simctl erase all Clearing the contents of my ~/Library/Developer/Xcode/UserData/Previews folder. Clearing the contents of my ~/Library/Developer/Xcode/DerivedDatas folder. Using xcrun simctl --set previews delete all Restarting macOS and Xcode The problem seems tpbe related to my project. When creating a fresh new project using "Storyboard" as interface and adding a SwiftUI file, the preview works fine. However, this does not help when working on my existing project... I generated a preview diagnostics report. I am using Xcode 16.0 on macOS 15.0
3
2
125
3d