Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftData/ModelSnapshot.swift:46: Fatal error: A ModelSnapshot must be initialized with a known-keys dictionary
I'm running into a crash when trying to delete an item from a list that's loaded using SwiftData. The app works fine when selecting or displaying the data, but the moment I confirm a deletion, it crashes with this error: SwiftData/ModelSnapshot.swift:46: Fatal error: A ModelSnapshot must be initialized with a known-keys dictionary This happens right after I delete an item from the list using modelContext.delete(). I’ve double-checked that the item exists and is valid, and I'm not sure what I'm doing wrong. The data is loaded using @Query and everything seems normal until deletion. For further information, I have tried this on a new IOS project where I have one super Model class with a cascading relationship on a child class. When trying to delete the parent class while connected to one or more children, it still gives me the error. The same thing is happening with my original project. Class A has a relationship (cascading) with Class B. Attempting to delete Class A while there are relationships with Class B throws this error. If anyone has experienced this or knows what causes it, please let me know. I’m not even sure where to start debugging this one. Thanks in advance!
2
1
123
3w
SwiftUI FileManager MacOS moving a file
Until a few days ago, I had a bit of code that could download a file from elsewhere to my home drive, "Users/eric". Today, the code downloads the file to "locat", but the following no longer works let _ = try fileManager.copyItem(atPath: locat, toPath: "/Users/eric/file.txt" ) After a careful search, I've changed the network to allow Network connections, and set User Selected and Downloads Folder to Read/Write without any luck. I am using Catalina and SwiftUI on a recent Mac (2023). As well, it was working just a few days ago. Any ideas or pointers?
1
0
57
May ’25
Incorrect text layout
This text is cut off for some unknown reason, but if you explicitly specify the default font, it is displayed correctly. Various solutions like .fixedSize(horizontal:,), frame(maxWidth:), lineLimit() do not solve the problem. Any other text does not have such problems. The bug is reproduced on iPhone 12 (iOS 18.4.1) public var body: some View { Text("Включите уведомления, чтобы первыми узнавать о новых коллекциях, эксклюзивных предложениях и статусе доставки") .padding(.horizontal) // .font(.system(size: 17)) // it works correctly with this }
2
0
90
May ’25
Opening FileDocument with URL → should only be called in the main thread
Its document says openDocument can open a document at a specific URL. So I've saved a model as a JSON object with its URL and a bookmark as Data. With its security-scoped bookmark data resolved, I am able to open a document except that the app will crash right after opening a document. Console says should only be called in the main thread struct ContentView: View { @EnvironmentObject var bookmarkViewModel: BookmarkViewModel var body: some View { VStack { } .onAppear { loadBookmarks() } } extension ContentView { func loadBookmarks() { print("1 \(Thread.current)") // NSMainThread Task { for bookmarkItem in bookmarkViewModel.bookmarkItems { // resolving a security-scoped bookmark print("2 \(Thread.current)") // NSMainThread if let _ = resolveBookmark(bookmarkData: bookmarkItem.bookmarkData) { print("3 \(Thread.current)") // NSMainThread do { print("4 \(Thread.current)") // NSMainThread try await openDocument(at: bookmarkItem.bookmarkURL) print("5 \(Thread.current)") // NSMainThread } catch { print("\(error.localizedDescription)") } } } } } } Well, the application is on the main thread. I've checked every line before and after opening a document with its URL. Call what on the main thread? This is confusing. Thanks. class BookmarkViewModel: ObservableObject { @Published var bookmarkItems: [BookmarkItem] = [] var defaultFileManager: FileManager { return FileManager.default } var documentURL: URL? { ... } init() { fetchBookmarkItems() } func fetchBookmarkItems() { bookmarkItems.removeAll() if let documentURL { let bookmarkFolderURL = documentURL.appending(path: "MyApp").appending(path: "Bookmarks") do { let contents = try defaultFileManager.contentsOfDirectory(atPath: bookmarkFolderURL.path) for content in contents { ... let fileURL = bookmarkFolderURL.appending(path: content) let data = try Data(contentsOf: fileURL) let bookmarkItem = try JSONDecoder().decode(BookmarkItem.self, from: data) bookmarkItems.append(bookmarkItem) } } catch { print("Error fetching folder content: \(error.localizedDescription)") } } } } struct BookmarkItem: Codable, Hashable { let bookmarkURL: URL let date: Date let bookmarkData: Data let open: Bool }
4
0
68
3w
How do I size a UITextView with scroll disabled?
tl;dr: UITextView does not auto layout when isScrollEnabled = false I have a screen with multiple UITextViews on it, contained within a ScrollView. For each textview, I calculate the height needed to display the entire content in SwiftUI and set it using the .frame(width:height:) modifier. The UITextView will respect the size passed in and layout within the container, but since UITextView is embedded within a UIScrollView, when a user attempts to scroll on the page, often they will scroll within a UITextView block rather than the page. They currently need to scroll along the margins outside of the textview to get the proper behavior. Since I am already calculating the height to display the text, I don't want the UITextView to scroll. However, when I set isScrollEnabled = false, the text view displays in a single long line that gets truncated. I have tried Setting various frame/size attributes but that seems to have zero affect on the layout. Embedding the textView within a UIView, and then sizing the container, but then the textView does not display at all. Setting a fixed size textContainer in the layoutManager but did not work. There's a lot of code so I can't copy/paste it all, but generally, it looks like struct SwiftUITextEditor: View { @State var text: AttributedString = "" var body: some View { ZStack { MyTextViewRepresentable(text: $text) } .dynamicallySized(from: $text) } } struct MyTextViewRepresentable: UIViewRepresentable { @Binding var text: AttributedString let textView = UITextView(usingTextLayoutManager: true) func makeUIView(context: Context) -> UITextView { textView.attributedText = text textView.isScrollEnabled = false } ... }
1
0
55
May ’25
NavigationStack within NavigationSplitView's detail column clears the path when disappearing
I'd like to persist the path on a sidebar selection, so when user comes back to the sidebar selection, they land where they were before. Unexpectedly, the path gets cleared when sidebarSelection is changed from the NavigationStack that uses the path to something else. Is this an intended behavior? How to workaround it? Using TabView is one way, but TabView has its own problems, so I'm wondering if there's a solution within NavigationSplitView first. Here is a minimal reproduce of the issue: struct Home2: View { private enum SidebarSelection: CaseIterable, Identifiable { var id: Self { self } case files, tags } @State private var sidebarSelection: SidebarSelection? = .files @State private var path: [Int] = [] var body: some View { NavigationSplitView { List(SidebarSelection.allCases, selection: $sidebarSelection) { selection in switch selection { case .files: Label("Files", image: "custom.square.stack") case .tags: Label("Tags", systemImage: "grid") } } } detail: { switch sidebarSelection { case .files: NavigationStack(path: $path) { Subview(depth: 1) .navigationDestination(for: Int.self) { Subview(depth: $0) } } case .tags: Text("Tags") default: EmptyView() } } .onChange(of: path) { print("\(path.count)") } } } struct Subview: View { let depth: Int var body: some View { List { NavigationLink("Next: \(depth + 1)", value: depth + 1) } .navigationTitle("Depth \(depth)") } } #Preview("Home2") { Home2() }
4
0
62
May ’25
iOS 18.4.1 breaks SwiftUI's DocumentGroup?
In iOS 18.4.1, DocumentGroup contains the DocumentView twice. (this may cause issues with alerts) To reproduce (iOS 18.4): In XCode Version 16.3 (16E140), create new project. Choose iOS, "Document App". No need to make code changes. Compile and run app on iOS 18.4 (simulator or device). in iOS (sim or device): Tap create document (once the app launched). in XCode: click "Debug View Hierarchy" in XCode: rotate the view Hierarch to reveal duplicated Document View hierarchies (2 Document Hosting Controllers), see screenshot. This probably affects alert view... I get warnings and it does not work properly (used to work ok on previous versions). Previous versions To compare with previous versions of iOS, run the same code and procedure on iOS 18.3 for example (see screenshot). Will report on Feedback assistant as well...
7
1
170
3w
Checking the contents of a TextField variable method not working
Hoping someone can help me with this… The error is… Generic parameter ‘/‘ cannot be inferred. .multilineTextAlignment(.center) .onAppear(perform: { var checkFirstCardLatitude = cards.firstCardLatitude let charArray = Array(checkFirstCardLatitude) let allowed: [Character] = ["-", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] for char in charArray { if char != allowed { cards.firstCardLatitude = "000.000000" // Reset Text Field } } })
26
0
248
May ’25
Reshield apps after certain time?
So I have been working with the screen time api. however I still cant get it to work to reshield certain apps after a certain time because for example Dispatch Queue just gets terminated after a certain time. This is my code right now but the reshielding doesn't get called. Please help I have been working on this since weeks and weeks. import ManagedSettings import DeviceActivity import Foundation class ShieldActionExtension: ShieldActionDelegate { let store = ManagedSettingsStore() let center = DeviceActivityCenter() override func handle(action: ShieldAction, for application: ApplicationToken, completionHandler: @escaping (ShieldActionResponse) -> Void) { switch action { case .primaryButtonPressed: // Unshield the app store.shield.applications?.remove(application) // Encode and persist ApplicationToken if let encoded = try? PropertyListEncoder().encode([application]) { UserDefaults(suiteName: "group.Organization.BrainRipe.cmonnow")?.set(encoded, forKey: "StoredApplicationTokens") } let unshieldDurationMinutes = 2 let now = Date() guard let endDate = Calendar.current.date(byAdding: .minute, value: unshieldDurationMinutes, to: now) else { completionHandler(.close) return } let activityName = DeviceActivityName("com.myapp.shield.reapply") let schedule = DeviceActivitySchedule( intervalStart: Calendar.current.dateComponents([.hour, .minute], from: now), intervalEnd: Calendar.current.dateComponents([.hour, .minute], from: endDate), repeats: false ) do { try center.startMonitoring(activityName, during: schedule) } catch { print("Error starting monitoring: \(error)") } completionHandler(.close) case .secondaryButtonPressed: completionHandler(.defer) @unknown default: fatalError("Unhandled ShieldAction case.") } } } import DeviceActivity import ManagedSettings import Foundation // Optionally override any of the functions below. // Make sure that your class name matches the NSExtensionPrincipalClass in your Info.plist. class DeviceActivityMonitorExtension: DeviceActivityMonitor { let store = ManagedSettingsStore() override func intervalDidStart(for activity: DeviceActivityName) { super.intervalDidStart(for: activity) // Handle the start of the interval. } override func intervalDidEnd(for activity: DeviceActivityName) { guard let data = UserDefaults(suiteName: "group.Organization.BrainRipe.cmonnow")?.data(forKey: "StoredApplicationTokens"), let tokens = try? PropertyListDecoder().decode([ApplicationToken].self, from: data) else { return } let tokenSet = Set(tokens) if store.shield.applications == nil { store.shield.applications = tokenSet } else { store.shield.applications?.formUnion(tokenSet) } // Clear tokens after use UserDefaults(suiteName: "group.Organization.BrainRipe.cmonnow")?.removeObject(forKey: "StoredApplicationTokens") } }
1
0
79
May ’25
DatePicker .graphical style: Inconsistent animation behavior when selecting out-of-range dates
Hi everyone, I’ve noticed an inconsistency in the behavior of SwiftUI’s DatePicker when using the .graphical style with a bounded date range (in:). When a user selects a date (month or year) outside the allowed range: If it's before the lower bound, the picker animates smoothly to the lower bound. BUT if the selected date is after the upper bound, the picker immediately jumps to the upper bound without animation. Note: Using .graphical style with displayedComponents: [.date]. Is this a known issue, and is there any recommended workaround or timeline for a fix? Or is this the intended behavior?
2
0
68
May ’25
A proper design approach for implementing a data logger using BLE in an iOS app.
Thank you for always reading my questions. This time, I'd like to ask some specific questions to gain a deeper understanding of iOS CoreBluetooth. In the previous question, we learned that although iOS can perform BLE scanning in the background, it is not suitable for use as a data logger. I was also taught that when using it as a data logger, the iOS app should use GATT communication, and that instead of reading data from the device one by one, it is recommended to store large amounts of data on the device and connect at an appropriate time (such as when the iOS app enters the foreground) to retrieve the data all at once. My requirements are the same as last time. I want to send data from a device equipped with some kind of sensor via BLE and display it in a graph in the iOS app. Data should be acquired every few to tens of seconds and reflected immediately in the graph. Measurements may take up to 24 hours at most. I would like to avoid making any major changes to the device. Also, it is unclear whether there will be enough memory for the data logger for 24 hours. Therefore, I am first looking for an appropriate communication method for the iOS app. iOS is smart and convenient, so I think users will check the measurement status every time they use this iOS app.Therefore, I want to be able to check the changes from the start of measurement to the present in a graph as soon as the app is launched. I would like to measure data from multiple devices (e.g. 5 devices) at the same time. I have a question based on the above requirements. When thinking about the best way to avoid making changes to the device, the only way I could come up with, as someone with insufficient iOS technology, is to keep the connection open via GATT communication and continue to obtain data. However, does iOS GATT communication have any limitations in this regard? Will the OS automatically disconnect GATT communication at a certain time? Also, if that happens, is there a way to automatically reconnect and obtain the data? Is it possible to smoothly obtain data using iOS GATT communication without any particular restrictions even in the background? Are any other permissions required? Regarding the sixth requirement. Until last time, with BLE scanning, even if there were multiple devices, the iOS app could measure the data for as many devices as it wanted, but this time, how many devices can be read? In the case of GATT communication with iOS CoreBluetooth, can multiple devices maintain a long connection? Or is it basically better to have one device per connection when creating such an app for iOS? I would like to know if there are any restrictions or points to be careful of when using GATT communication with multiple devices. I'm sorry for broadening my question, but if neither question 1 nor question 2 works, it will put a burden on the design of the device. If data is stored on the device, is it possible to automatically and periodically connect to the device at a set time interval (for example, once an hour, allowing for some margin of error) when the iOS app is in the background, and obtain log data from the device? If you can think of any other best methods, please feel free to let me know. Also, I'd be happy if you could reply with any reference materials or URLs. Please note that our response may be delayed.
0
0
94
May ’25
Scene.windowIdealSize(.fitToContent) seems not working
Hi everyone, Something didn't work in my environment so I wrote some demo code: import SwiftUI @main struct DemoApp: App { var body: some Scene { WindowGroup { Color.accentColor.opacity(1/4) .frame(idealWidth: 800, idealHeight: 800) } .windowIdealSize(.fitToContent) } } I expected a 800*800 window (then +28pt top) using .windowIdealSize(.fitToContent). Otherwise I can't control these views that use up available space such as Color, Spacer, GeometryReader, etc. Was I missing something? Or this is a problem or intended framework design? Environments: macOS 15.4.1 (24E263) and 15.5 beta 4 (24F5068b) Xcode 16.3 (16E140)
2
0
49
May ’25
Cannot reassign worldTracking / planeDetection providers in my PlacementManager when switching environments
Environment Xcode: 16.2 VisionOS SDK 2.4 Swift 6.1 Targets: Apple Vision Pro (immersive space) Frameworks: ARKit, RealityKit, SwiftUI What I’m Trying to Do I have a view-model class PlacementManager that holds two AR providers: private var worldTracking: WorldTrackingProvider private var planeDetection: PlaneDetectionProvider I want to dynamically replace these providers in a setEnvironment(_:) method (so I can save/clear a JSON scene and restart ARKit). What’s Happening If I declare them as : private let worldTracking = WorldTrackingProvider() private let planeDetection = PlaneDetectionProvider() I get compile-errors when I later do: self.worldTracking = newWorldTracking // Cannot assign to property: 'worldTracking' is a 'let' constant If I change them to un-initialized vars: private var worldTracking: WorldTrackingProvider private var planeDetection: PlaneDetectionProvider then in my init() I get: self used in property access 'worldTracking' before all stored properties are initialized Code snipet @Observable final class PlacementManager : ObservableObject { private var worldTracking: WorldTrackingProvider private var planeDetection: PlaneDetectionProvider // … other props … @MainActor init() { // error: self.worldTracking used before init… planeAnchorHandler = PlaneAnchorHandler(rootEntity: root) persistenceManager = PersistenceManager( worldTracking: worldTracking, rootEntity: root ) // … } @MainActor func setEnvironment(env: Environnement) async { let newWorldTracking = WorldTrackingProvider() let newPlaneDetection = PlaneDetectionProvider() try await appState!.arkitSession.run( [ newWorldTracking, newPlaneDetection ] ) self.worldTracking = newWorldTracking self.planeDetection = newPlaneDetection // … } } What I’ve Tried Giving them default values at declaration (= WorldTrackingProvider()) Initializing them at the top of init() before any use Passing the new providers into arkitSession.run(...) My Question What is the recommended Swift-style pattern to declare and reassign these ARKit provider properties so that: They’re fully initialized before use in init(), and I can swap them out later in setEnvironment(...) without compiler errors? Any pointers (or links to forum threads / docs) would be greatly appreciated!
0
0
55
May ’25
List Layout Breaks in NavigationStack When a View Exceeds Screen Width
This is a bug report. FB17433985 The layout of the following ContentView appears correctly when it is outside a NavigationStack. However, when the same view is placed inside a NavigationStack, the layout breaks. It seems that the width of the List is being affected by the width of the buttonsView, which exceeds the screen width. In my testing, this issue occurs on iOS 18.4 and later, but does not occur on iOS 18.2 or iOS 17.5. Workaround I found: Remove the fixed width modifier from the Button If anyone knows of other ways to resolve this issue without affecting the layout, I would appreciate it if you could share them. import SwiftUI let values = (1...100).map { $0 } let buttonTitles = (1...9).map { "Button\($0)" } struct ContentView: View { var body: some View { VStack { List { Section { ForEach(values.indices, id: \.self) { val in HStack { Text("Index: \(val)") } } } } buttonsView } } private var buttonsView: some View { HStack { ForEach(0..<buttonTitles.count, id: \.self) { index in Button() { } label: { Image(systemName: "square.and.arrow.up") .resizable() .frame(width: 48, height: 48) } } } } } @main struct ButtonShapeBugApp: App { var body: some Scene { WindowGroup { if true { NavigationStack { ContentView() } } else { ContentView() } } } } Environment: Xcode Version 16.3 (16E140) iPhone 18.4.1 real device iPhone SE3rd 18.4 simulator Expect layout Broken layout(9 buttons) Broken layout(10 buttons)
2
0
53
May ’25
How to reopen a closed SwiftUI WindowGroup window programmatically without user interaction?
I’m building a macOS app using SwiftUI with a WindowGroup(id: "rootWindow") for the main UI. The app shows a countdown timer, and the timer continues to run even after the user closes the main window (clicks the red "X"). When the timer reaches 0, I want to automatically reopen that window and bring the app to the front. I’m currently using the following code to bring the app to the foreground and show the window when the app is still open (but not focused/resign active state): NSApp.activate(ignoringOtherApps: true) NSApp.windows.forEach { window in if window.identifier?.rawValue.starts(with: "rootWindow") { window.makeKeyAndOrderFront(nil) } } However, this doesn’t work when the window has been closed. At that point, NSApp.windows no longer contains my SwiftUI window, and I have no reference to recreate or reopen it. I also cannot use openWindow environment value as it requires a view. How can I programmatically reopen a SwiftUI WindowGroup window after it’s been closed, without requiring any user interaction (like clicking the Dock icon)?
2
0
51
May ’25
[SwiftUI] Gesture Conflict: simultaneousGesture Causes Incorrect Gesture Recognition in iOS 18
Subject: SwiftUI Gesture Conflict in iOS 18: Simultaneous Recognition of Drag and Tap Gestures Description: In SwiftUI on iOS 18 and above, we've identified an issue with gesture handling that affects user experience. When implementing .simultaneousGesture(DragGesture()), the system incorrectly recognizes and processes both drag and tap gestures concurrently, resulting in unintended behavior. Technical Details: Environment: SwiftUI, iOS 18+ Issue: Simultaneous recognition of horizontal drag gestures and vertical scroll/tap gestures Current Behavior: Both vertical and horizontal scrolling occur simultaneously when using .simultaneousGesture(DragGesture()) Expected Behavior: Gestures should be properly disambiguated to prevent concurrent scrolling in multiple directions Impact: This behavior significantly impacts user experience, particularly in custom carousel implementations and other UI components that rely on precise gesture handling. The simultaneous recognition of both gestures creates a confusing and unpredictable interaction pattern. Steps to Reproduce: Create a SwiftUI view with horizontal scrolling (e.g., custom carousel) Implement .simultaneousGesture(DragGesture()) Add tap gesture recognition to child views Run on iOS 18 Attempt to scroll horizontally Observed Result: Both horizontal dragging and vertical scrolling/tapping are recognized and processed simultaneously, creating an inconsistent user experience. Expected Result: The system should properly disambiguate between horizontal drag gestures and vertical scroll/tap gestures, allowing only one type of gesture to be recognized at a time based on the user's intent. Please let me know if you need any additional information or reproduction steps.
0
0
34
Apr ’25
onReceive(_:perform:) on Frontmost Window Only?
I have a simple document-based application for macOS. struct ContentView: View { @Binding var document: TextDocument var body: some View { .onReceive(NotificationCenter.default.publisher(for: .notificationTextWillAppendSomeTextt), perform: { _ in }) VStack { TextEditor(text: $document.text) } } } extension Notification.Name { static let notificationTextWillAppendSomeTextt = Notification.Name("TextWillAppendSomeText") } Suppose that my application currently has three tabs. If I call a menu command through post(name:object:) this menu command call will affect all three of them. This stackoverflow topic talks about it, too. So how could I tell which window should get a call and others don't? Thanks.
3
0
56
May ’25
Help getting elements from SwiftData in AppIntent for widget
Hello, I am trying to get the elements from my SwiftData databse in the configuration for my widget. The SwiftData model is the following one: @Model class CountdownEvent { @Attribute(.unique) var id: UUID var title: String var date: Date @Attribute(.externalStorage) var image: Data init(id: UUID, title: String, date: Date, image: Data) { self.id = id self.title = title self.date = date self.image = image } } And, so far, I have tried the following thing: AppIntent.swift struct ConfigurationAppIntent: WidgetConfigurationIntent { static var title: LocalizedStringResource { "Configuration" } static var description: IntentDescription { "This is an example widget." } // An example configurable parameter. @Parameter(title: "Countdown") var countdown: CountdownEntity? } Countdowns.swift, this is the file with the widget view struct Provider: AppIntentTimelineProvider { func placeholder(in context: Context) -> SimpleEntry { SimpleEntry(date: Date(), configuration: ConfigurationAppIntent()) } func snapshot(for configuration: ConfigurationAppIntent, in context: Context) async -> SimpleEntry { SimpleEntry(date: Date(), configuration: configuration) } func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<SimpleEntry> { var entries: [SimpleEntry] = [] // Generate a timeline consisting of five entries an hour apart, starting from the current date. let currentDate = Date() for hourOffset in 0 ..< 5 { let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)! let entry = SimpleEntry(date: entryDate, configuration: configuration) entries.append(entry) } return Timeline(entries: entries, policy: .atEnd) } // func relevances() async -> WidgetRelevances<ConfigurationAppIntent> { // // Generate a list containing the contexts this widget is relevant in. // } } struct SimpleEntry: TimelineEntry { let date: Date let configuration: ConfigurationAppIntent } struct CountdownsEntryView : View { var entry: Provider.Entry var body: some View { VStack { Text("Time:") Text(entry.date, style: .time) Text("Title:") Text(entry.configuration.countdown?.title ?? "Default") } } } struct Countdowns: Widget { let kind: String = "Countdowns" var body: some WidgetConfiguration { AppIntentConfiguration(kind: kind, intent: ConfigurationAppIntent.self, provider: Provider()) { entry in CountdownsEntryView(entry: entry) .containerBackground(.fill.tertiary, for: .widget) } } } CountdownEntity.swift, the file for the AppEntity and EntityQuery structs struct CountdownEntity: AppEntity, Identifiable { var id: UUID var title: String var date: Date var image: Data var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(title)") } static var defaultQuery = CountdownQuery() static var typeDisplayRepresentation: TypeDisplayRepresentation = "Countdown" init(id: UUID, title: String, date: Date, image: Data) { self.id = id self.title = title self.date = date self.image = image } init(id: UUID, title: String, date: Date) { self.id = id self.title = title self.date = date self.image = Data() } init(countdown: CountdownEvent) { self.id = countdown.id self.title = countdown.title self.date = countdown.date self.image = countdown.image } } struct CountdownQuery: EntityQuery { typealias Entity = CountdownEntity static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Countdown Event") static var defaultQuery = CountdownQuery() @Environment(\.modelContext) private var modelContext // Warning here: Stored property '_modelContext' of 'Sendable'-conforming struct 'CountdownQuery' has non-sendable type 'Environment<ModelContext>'; this is an error in the Swift 6 language mode func entities(for identifiers: [UUID]) async throws -> [CountdownEntity] { let countdownEvents = getAllEvents(modelContext: modelContext) return countdownEvents.map { event in return CountdownEntity(id: event.id, title: event.title, date: event.date, image: event.image) } } func suggestedEntities() async throws -> [CountdownEntity] { // Return some suggested entities or an empty array return [] } } CountdownsManager.swift, this one just has the function that gets the array of countdowns func getAllEvents(modelContext: ModelContext) -> [CountdownEvent] { let descriptor = FetchDescriptor<CountdownEvent>() do { let allEvents = try modelContext.fetch(descriptor) return allEvents } catch { print("Error fetching events: \(error)") return [] } } I have installed it in my phone and when I try to edit the widget, it doesn't show me any of the elements I have created in the app, just a loading dropdown for half a second: What am I missing here?
0
0
50
Apr ’25
Lists, Generics, Views, Navigation Link, SwiftData - ForEach can't pass a binding anymore.
I'm trying out putting most of my business logic in a Protocol that my @Model can conform to, but I'm running into a SwiftUI problem with a Binding that does not get magically offered up like it does when it the subview is not generic. I have a pretty basic List with a ForEach that now can't properly pass to a generic view based on a protocol. When I try to make a binding manually in the row it says that "item is immutable"... but that also doesn't help me with the NavigationLink? Which is seeing the Binding not the ? But before when the subview was concrete to Thing, it took in the and made its own Binding once it hit the view. I'm unclear on precisely where the change happens and what I can do to work around it. Before I go rearchitecting everything... is there a fix to get the NavigationLink to take on the object like before? What needs to be different? I've tried a number of crazy inits on the subview and they all seem to come back to saying either it can't figure out how to pass the type or I'm trying to use the value before it's been initialized. Have I characterized the problem correctly? Thanks! (let me know if I forgot a piece of code, but this should be the List, the Model/Protocol and the subview) import SwiftUI import SwiftData struct ThingsView: View {     @Environment(\.modelContext) var modelContext     @Query var items: [Thing]          var body: some View {         NavigationStack {             List {                 ForEach(items) { item in                     NavigationLink(value: item) {                         VStack(alignment: .leading) {                             Text(item.textInfo)                                 .font(.headline)                                                          Text(item.timestamp.formatted(date: .long, time: .shortened))                         }                     }                 }.onDelete(perform: deleteItems)             }             .navigationTitle("Fliiiing!") //PROBLEM HERE: Cannot convert value of type '(Binding<Thing>) -> EditThingableView<Thing>' to expected argument type '(Thing) -> EditThingableView<Thing>'             .navigationDestination(for: Thing.self, destination: EditThingableView<Thing>.init) #if os(macOS)             .navigationSplitViewColumnWidth(min: 180, ideal: 200) #endif             .toolbar { #if os(iOS)                 ToolbarItem(placement: .navigationBarTrailing) {                     EditButton()                                      } #endif                 ToolbarItem {                     Button(action: addItem) {                         Label("Add Item", systemImage: "plus")                     }                 }                 ToolbarItem {                     Button("Add Samples", action: addSamples)                 }             }         }     }          func addSamples() {         withAnimation {             ItemSDMC.addSamples(context: modelContext)         }     }          private func addItem() {         withAnimation {             let newItem = ItemSDMC("I did a thing!")             modelContext.insert(newItem)         }     }          func deleteItems(_ indexSet:IndexSet) {         withAnimation {             for index in indexSet {                 items[index].delete(from: modelContext)             }         }     } } #Preview {     ThingsView().modelContainer(for: ItemSDMC.self, inMemory: true) } import Foundation import SwiftData protocol Thingable:Identifiable {     var textInfo:String { get set }     var timestamp:Date { get set } } extension Thingable {     var thingDisplay:String {         "\(textInfo) with \(id) at \(timestamp.formatted(date: .long, time: .shortened))"     } } extension Thingable where Self:PersistentModel {     var thingDisplayWithID:String {         "\(textInfo) with modelID \(self.persistentModelID.id) in \(String(describing: self.persistentModelID.storeIdentifier)) at \(timestamp.formatted(date: .long, time: .shortened))"     } } struct ThingLite:Thingable, Codable, Sendable {     var textInfo: String     var timestamp: Date     var id: Int } @Model final class Thing:Thingable {     //using this default value requires writng some clean up logic looking for empty text info.     var textInfo:String = ""     //using this default value would require writing some data clean up functions looking for out of bound dates.     var timestamp:Date = Date.distantPast          init(textInfo: String, timestamp: Date) {         self.textInfo = textInfo         self.timestamp = timestamp     } } extension Thing {     var LiteThing:ThingLite {         ThingLite(textInfo: textInfo, timestamp: timestamp, id: persistentModelID.hashValue)     } } import SwiftUI struct EditThingableView<DisplayItemType:Thingable>: View {     @Binding var thingHolder: DisplayItemType          var body: some View {                  VStack {             Text(thingHolder.thingDisplay)             Form {                 TextField("text", text:$thingHolder.textInfo)                 DatePicker("Date", selection: $thingHolder.timestamp)             }                      } #if os(iOS)         .navigationTitle("Edit Item")         .navigationBarTitleDisplayMode(.inline) #endif     } } //NOTE: First sign of trouble //#Preview { //    @Previewable var myItem = Thing(textInfo: "Example Item for Preview", timestamp:Date()) //    EditThingableView<Thing>(thingHolder: myItem) //}
4
0
90
May ’25
[SwiftUI] SecureEntry Autofill in Dark Mode
When using New Password Autofill in Dark Mode, it appears that SecureEntry sets the background color to white and applies a yellow-ish overlay, but doesn't adapt the foreground text color accordingly. This gives the illusion that the SecureEntry field is empty, as we have white text on a white background. Is there a holistic and SwiftUI-native way of fixing this?
0
0
23
Apr ’25