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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Issue with .itemProvider on macOS 15.1
I have a List with draggable items. According to this thread (https://developer.apple.com/forums/thread/664469) I had to use .itemProvider instead of .onDrag, because otherwise the selection of the list will not work anymore. The items in my list refer to a file URL. So the dragging allowed to copy the files to the destination of the drag & drop. Therefore I used this code .itemProvider { let url = ....... // get the url with an internal function return NSItemProvider(object: url as NSURL) } Since the update to macOS 15.1 this way isn't working anymore. It just happens nothing. I also tried to use .itemProvider { let url = .... return NSItemProvider(contentsOf: url) ?? NSItemProvider(object: url as NSURL) } but this doesn't work too. The same way with .onDrag works btw. .onDrag { let url = ....... // get the url with an internal function return NSItemProvider(object: url as NSURL) } but as I wrote, this will break the possibility to select or to use the primaryAction of the .contextMenu. Is this a bug? Or is my approach wrong and is there an alternative?
5
0
160
3w
macOS SwiftUI document app always shows file picker on startup
DESCRIPTION OF PROBLEM When my Document-based macOS SwiftUI app starts up, it always presents a document picker. I would like it to open any documents that were open when the app last quit, and if none were open, open an "Untitled" document. I understand that there is a setting in System Settings-> Desktop & Dock ("Close windows when quitting an application") that will cause windows to reopen when it is turned off, but I'd like to give users a chance to opt-in for reopening docs even when that is turned on, since it is difficult to find, on by default, and might not be the desired behavior for all apps. I don't see any way to get a list of currently open documents to persist them at shutdown. And even if that's considered a bad idea, I'd at least like a way to prevent the Document picker from being shown at startup and instead create an Untitled document if no documents were open. Ideally, I'd like a way to provide this functionality in SwiftUI that doesn't require macOS 15 or later STEPS TO REPRODUCE Create a SwiftUI macOS document application in Xcode using the provided template, Give it any name you want Run it, create a new ".exampletext" document, save it. Quit the app with the document open. Re-run the app, document picker is shown. Cancel the document picker and quit the app with no windows shown. Re-run the app, document picker is shown.
2
0
136
1w
Discovered a bug where Alert button colors are changed by the tint modifier.
I used .tint(.yellow) to change the default back button color. However, I noticed that the color of the alert button text, except for .destructive, also changed. Is this a bug or Apple’s intended behavior? this occurs in iOS 18.1 and 18.1.1 Below is my code: // App struct TintTestApp: App { var body: some Scene { WindowGroup { MainView() .tint(.yellow) } } } // MainView var mainContent: some View { Text("Next") .foregroundStyle(.white) .onTapGesture { isShowingAlert = true } .alert("Go Next View", isPresented: $isShowingAlert) { Button("ok", role: .destructive) { isNextButtonTapped = true } Button("cancel", role: .cancel) { } } } thank you!
0
0
47
15h
Since iOS 18.1, the color of Alert buttons has been affected by the tint modifier.
I used .tint(.yellow) to change the default back button color. However, I noticed that the color of the alert button text, except for .destructive, also changed. Is this a bug or Apple’s intended behavior? Thank you! Below is my code: // App struct tintTestApp: App { var body: some Scene { WindowGroup { MainView() .tint(.yellow) } } // MainView var mainContent: some View { Text("Next") .foregroundStyle(.white) .onTapGesture { isShowingAlert = true } .alert("Go Next View", isPresented: $isShowingAlert) { Button("ok", role: .destructive) { isNextButtonTapped = true } Button("cancel", role: .cancel){} } }
2
1
41
15h
In SwiftUI in iOS 18.1, `SectionedFetchRequest` is not refreshed when changes are done to the fetched entity's attributes.
Hi, This issue started with iOS 18, in iOS 17 it worked correctly. I think there was a change in SectionedFetchRequest so maybe I missed it but it did work in iOS 17. I have a List that uses SectionedFetchRequest to show entries from CoreData. The setup is like this: struct ManageBooksView: View { @SectionedFetchRequest<Int16, MyBooks>( sectionIdentifier: \.groupType, sortDescriptors: [SortDescriptor(\.groupType), SortDescriptor(\.name)] ) private var books: SectionedFetchResults<Int16, MyBooks> var body: some View { NavigationStack { List { ForEach(books) { section in Section(header: Text(section.id)) { ForEach(section) { book in NavigationLink { EditView(book: book) } label: { Text(book.name) } } } } } .listStyle(.insetGrouped) } } } struct EditView: View { private var book: MyBooks init(book: MyBooks) { print("Init hit") self.book = book } } Test 1: So now when I change name of the Book entity inside the EditView and do save on the view context and go back, the custom EditView is correctly hit again. Test 2: If I do the same changes on a different attribute of the Book entity the custom init of EditView is not hit and it is stuck with the initial result from SectionedFetchResults. I also noticed that if I remove SortDescriptor(\.name) from the sortDescriptors and do Test 1, it not longer works even for name, so it looks like the only "observed" change is on the attributes inside sortDescriptors. Any suggestions will be helpful, thank you.
1
0
84
1d
@Observable and didSet?
I'm in the process of migrating to the Observation framework but it seems like it is not compatible with didSet. I cannot find information about if this is just not supported or a new approach needs to be implemented? import Observation @Observable class MySettings { var windowSize: CGSize = .zero var isInFullscreen = false var scalingMode: ScalingMode = .scaled { didSet { ... } } ... } This code triggers this error: Instance member 'scalingMode' cannot be used on type 'MySettings'; did you mean to use a value of this type instead? Anyone knows what needs to be done? Thanks!
8
3
3.1k
Jun ’23
Customizing Tables in SwiftUI
Hi, How to customize tables in SwiftUI its color background for example, the background modifier doesn't work ? how to change separator lines ? rows background colors ? give header row different colors to its text and background color ? Kind Regards
1
0
54
15h
SwiftUI not observing SwiftData changes
I have an app with the following model: @Model class TaskList { @Attribute(.unique) var name: String // Relationships var parentList: TaskList? @Relationship(deleteRule: .cascade, inverse: \TaskList.parentList) var taskLists: [TaskList]? init(name: String, parentTaskList: TaskList? = nil) { self.name = name self.parentList = parentTaskList self.taskLists = [] } } If I run the following test, I get the expected results - Parent has it's taskLists array updated to include the Child list created. I don't explicitly add the child to the parent array - the parentList relationship property on the child causes SwiftData to automatically perform the append into the parent array: @Test("TaskList with children with independent saves are in the database") func test_savingRootTaskIndependentOfChildren_SavesAllTaskLists() async throws { let modelContext = TestHelperUtility.createModelContext(useInMemory: false) let parentList = TaskList(name: "Parent") modelContext.insert(parentList) try modelContext.save() let childList = TaskList(name: "Child") childList.parentList = parentList modelContext.insert(childList) try modelContext.save() let fetchedResults = try modelContext.fetch(FetchDescriptor<TaskList>()) let fetchedParent = fetchedResults.first(where: { $0.name == "Parent"}) let fetchedChild = fetchedResults.first(where: { $0.name == "Child" }) #expect(fetchedResults.count == 2) #expect(fetchedParent?.taskLists.count == 1) #expect(fetchedChild?.parentList?.name == "Parent") #expect(fetchedChild?.parentList?.taskLists.count == 1) } I have a subsequent test that deletes the child and shows the parent array being updated accordingly. With this context in mind, I'm not seeing these relationship updates being observed within SwiftUI. This is an app that reproduces the issue. In this example, I am trying to move "Finance" from under the "Work" parent and into the "Home" list. I have a List that loops through a @Query var taskList: [TaskList] array. It creates a series of children views and passes the current TaskList element down into the view as a binding. When I perform the operation below the "Finance" element is removed from the "Work" item's taskLists array automatically and the view updates to show the removal within the List. In addition to that, the "Home" item also shows "Finance" within it's taskLists array - showing me that SwiftData is acting how it is supposed to - removed the record from one array and added it to the other. The View does not reflect this however. While the view does update and show "Finance" being removed from the "Work" list, it does not show the item being added to the "Home" list. If I kill the app and relaunch I can then see the "Finance" list within the "Home" list. From looking at the data in the debugger and in the database, I've confirmed that SwiftData is working as intended. SwiftUI however does not seem to observe the change. ToolbarItem { Button("Save") { list.name = viewModel.name list.parentList = viewModel.parentTaskList try! modelContext.save() dismiss() } } To troubleshoot this, I modified the above code so that I explicitly add the "Finance" list to the "Home" items taskLists array. ToolbarItem { Button("Save") { list.name = viewModel.name list.parentList = viewModel.parentTaskList if let newParent = viewModel.parentTaskList { // MARK: Bug - This resolves relationship not being reflected in the View newParent.taskLists?.append(list) } try! modelContext.save() dismiss() } } Why does my explicit append call solve for this? My original approach (not manually updating the arrays) works fine in every unit/integration test I run but I can't get SwiftUI to observe the array changes. Even more strange is that when I look at viewModel.parentTaskList.taskLists in this context, I can see that the list item already exists in it. So my code effectively tries to add it a second time, which SwiftData is smart enough to prevent from happening. When I do this though, SwiftUI observes a change in the array and the UI reflects the desired state. In addition to this, if I replace my custom list rows with an OutlineGroup this issue doesn't manifest itself. SwiftUI stays updated to match SwiftData when I remove my explicit array addition. I don't understand why my views, which is passing the TaskList all the way down the stack via Bindable is not updating while an OutlineGroup does. I have a complete reproducible ContentView file that demonstrates this as a Gist. I tried to provide the source here but it was to much for the post. One other anecdote. When I navigate to the TaskListEditorScreen and open the TaskListPickerScreen I get the following series of errors: error: the replacement path doesn't exist: "/var/folders/07/3px_03md30v9n105yh3rqzvw0000gn/T/swift-generated-sources/@_swiftmacro_09SwiftDataA22UIChangeDetectionIssue20TaskListPickerScreenV9taskLists33_A40669FFFCF66BB4EEA5302BB5ED59CELL5QueryfMa.swift" I saw another post regarding these and I'm wondering if my issue is related to this. So my question is, do I need to handle observation of SwiftData models containing arrays differently in my custom views? Why do bindings not observe changes made by SwiftData but they observe changes made explicitly by me?
1
0
167
1w
Macos 15.2 beta 4 App Crash
I have a SwiftUI based program that has compiled and run consistently on previous macos versions. After upgrading to 15.2 beta 4 to address a known issue with TabView in 15.1.1, my app is now entering a severe hang and crashing with: "The window has been marked as needing another Update Contraints in Window pass, but it has already had more Update Constraints in Window passes than there are views in the window. .<SwiftUI.AppKitWindow: 0x11d82a800> 0x87 (2071) {{44,0},{1468,883}} en" Is there a known bug that could be causing this crash or known change in the underlying layout model?
0
0
75
19h
Horizontal window/map on visionOS
Hi, would anyone be so kind and try to guide me, which technologies, Kits, APIs, approaches etc. are useful for creating a horizontal window with map (preferrably MapKit) on visionOS using SwiftUI? I was hoping to achieve scenario: User can walk around and interact with horizontal map window and also interact with (3D) pins on the map. Similar thing was done by SAP in their "SAP Analytics Cloud" app (second image from top). Since I am complete beginner in this area, I was looking for a clean, simple solution. I need to know, if AR/RealityKit is necessary or is this achievable only using native SwiftUI? I tried using just Map() with .rotation3DEffect() which actually makes the map horizontal, but gestures on the map are out of sync and I really dont know, if this approach is valid or complete rubbish. Any feedback appreciated.
0
0
57
22h
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
11
0
581
Oct ’24
sourceImageURL in imagePlaygroundSheet isn't optional
I can't shake the "I don't think I did this correctly" feeling about a change I'm making for Image Playground support. When you create an image via an Image Playground sheet it returns a URL pointing to where the image is temporarily stored. Just like the Image Playground app I want the user to be able to decide to edit that image more. The Image Playground sheet lets you pass in a source URL for an image to start with, which is perfect because I could pass in the URL of that temp image. But the URL is NOT optional. So what do I populate it with when the user is starting from scratch? A friendly AI told me to use URL(string: "")! but that crashes when it gets forced unwrapped. URL(string: "about:blank")! seems to work in that it is ignored (and doesn't crash) when I have the user create the initial image (that shouldn't have a source image). This feels super clunky to me. Am I overlooking something?
0
0
58
1d
[iOS 18.2 Beta] LazyVGrid within NavigationStack breaks animations
Hello. There seems to be a bug specifically in the iOS 18.2 (both Beta 1 and 2) and not seen in the previous versions. The bug is: when LazyVGrid is nested inside NavigationStack and some elements of the LazyVGrid have animations, navigating into any nested view and then going back to the initial view with the LazyVGrid causes all animations to stop working. Here is the example code inline: struct ContentView: View { @State private var count: Int = 0 var body: some View { NavigationStack { LazyVGrid( columns: Array( repeating: GridItem(spacing: 0), count: 1 ), alignment: .center, spacing: 0 ) { VStack { Text(String(count)) .font(.system(size: 100, weight: .black)) .contentTransition(.numericText()) .animation(.bouncy(duration: 1), value: count) Button("Increment") { count += 1 } NavigationLink(destination: { Text("Test") }, label: { Text("Navigate") }) } } } .padding() } } Once you run the application on iOS 18.2 Beta (I've tried on a real device only), the steps to reproduce are: Tap on the "Increment button" You should see the number change with an animation Tap on the "Navigate" button Tap "Back" to go to the initial screen Tap "Increment" again The number changes without an animation I can confirm that this affects not only .contentTransition() animation but any animation within the LazyVGrid, I've tested this in my real app. Let me know if I can provide more details. Thank you!
4
0
142
6d
Share sheet configuration
I'm trying to configure the share sheet. My project uses techniques from the Apple Sample project called CoreDataCloudKitShare which is found here: https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users# In this sample code there's a "PersistenceController" which is an NSPersistentCloudKitContainer. In the "PersistenceController+SharingUtilities" file there are some extensions, and one of them is this: func configure(share: CKShare, with photo: Photo? = nil) { share[CKShare.SystemFieldKey.title] = "A cool photo" } This text "A cool photo" seems to be the only bespoke configuration of the share sheet within this project. I want to have more options to control the share sheet, does anyone know how this might be achieved? Thank you!
0
0
44
1d
Most idiotic problem with assign value to value?
Why assigning function.formula = formula does not change function.formula to formula in one go? It's always late one change behind. struct CustomFunction has defined .formula as @MainActor. I feel stupid. There is a part of code: struct CustomFormulaView: View { @Binding var function: CustomFunction @State var testFormula: String = "" @EnvironmentObject var manager: Manager .... .onChange(of: testFormula) { debugPrint("change of test formula: \(testFormula)") switch function.checkFormula(testFormula, on: manager.finalSize) { case .success(let formula): debugPrint("before Change: \(function.formula)") function.formula = formula // Nothing happens debugPrint("Test formula changed: \(testFormula)") debugPrint("set to success: \(formula)") debugPrint("what inside function? \(function.formula)") Task { //Generate Image testImage = await function.image( size: testImageSize), simulate: manager.finalSize) debugPrint("test image updated for: \(function.formula)") } .... and it produces this output when changed from 0.5 to 1.0 Debug: change of test formula: 1.0 Debug: before Change: 0.5 Debug: Test formula changed: 1.0 Debug: set to success: 1.0 Debug: what inside function? 0.5 Debug: test image updated for: 0.5 0.5 is an old value, function.formula should be 1.0 WT??
3
0
107
1d
@FetchRequest predicate is ignored if the context changes
I have a simple SwiftUI application with CoreData and two views. One view displays all "Place" objects. You can create new places and you can show the details for the place. Inside the second view you can add "PlaceItem"s to a place. The problem is that, once a new "PlaceItem" is added to the viewContext, the @NSFetchRequest seems to forget about its additional predicates, which I set in onAppear. Then every place item is shown inside the details view. Once I update the predicate manually (the refresh button), only the items from the selected place are visible again. Any idea how this can be fixed? Here's the code for my two views: struct PlaceView: View { @FetchRequest(sortDescriptors: []) private var places: FetchedResults<Place> @Environment(\.managedObjectContext) private var viewContext var body: some View { NavigationView { List(places) { place in NavigationLink { PlaceItemsView(place: place) } label: { Text(place.name ?? "") } } } .toolbar { ToolbarItem(placement: .primaryAction) { Button { let place = Place(context: viewContext) place.name = NSUUID().uuidString try! viewContext.save() } label: { Label("Add", systemImage: "plus") } } } .navigationTitle("Places") } } struct PlaceItemsView: View { @ObservedObject var place: Place @FetchRequest(sortDescriptors: []) private var items: FetchedResults<PlaceItem> @Environment(\.managedObjectContext) private var viewContext func updatePredicate() { items.nsPredicate = NSPredicate(format: "place == %@", place) } var body: some View { NavigationView { List(items) { item in Text(item.name ?? ""); } } .onAppear(perform: updatePredicate) .toolbar { ToolbarItem(placement: .primaryAction) { Button { let item = PlaceItem(context: viewContext) item.place = place item.name = NSUUID().uuidString try! viewContext.save() } label: { Label("Add", systemImage: "plus") } } ToolbarItem(placement: .navigationBarLeading) { Button(action: updatePredicate) { Label("Refresh", systemImage: "arrow.clockwise") } } } .navigationTitle(place.name ?? "") } } struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext var body: some View { NavigationView { PlaceView() } } } Thanks!
2
0
674
Feb ’22
AVSpeechUtterance problem
I see this error in the debugger: #FactoryInstall Unable to query results, error: 5 IPCAUClient.cpp:129 IPCAUClient: bundle display name is nil Error in destroying pipe Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 5476 on anonymousListener or serviceListener was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 5476 on anonymousListener or serviceListener was invalidated from this process.} on this function: func speakItem() { let utterance = AVSpeechUtterance(string: item.toString()) utterance.voice = AVSpeechSynthesisVoice(language: "en-GB") try? AVAudioSession.sharedInstance().setCategory(.playback) utterance.rate = 0.3 let synthesizer = AVSpeechSynthesizer() synthesizer.speak(utterance) } When running without the debugger, it will (usually) speak once, then it won't speak unless I tap the button that calls this function many times. I know AVSpeech has problems that Apple is long aware of, but I'm wondering if anyone has a work around. I was thinking there might be a way to call the destructor for AVSpeechUtterance and generate a new object each time speech is needed, but utterance.deinit() shows: "Deinitializers cannot be accessed"
0
0
68
1d
I am learning swift ui by mimicing stickies but i am facing richtexteditor problem
I am learning swift ui by mimicing stickies but i am having issue with richtextui Error ViewBridge to RemoteViewService Terminated: Error Domain=com.apple.ViewBridge Code=18 "(null)" UserInfo={com.apple.ViewBridge.error.hint=this process disconnected remote view controller -- benign unless unexpected, com.apple.ViewBridge.error.description=NSViewBridgeErrorCanceled} Why it is connecting to remote service when i develop it in local for mac UI error is this. I type cursor moves and no text displayed. changed color to everything some code import SwiftUI import AppKit struct RichTextEditor: NSViewRepresentable { @Binding var attributedText: NSAttributedString var isEditable: Bool = true var textColor: NSColor = .black var backgroundColor: NSColor = .white var font: NSFont = NSFont.systemFont(ofSize: 14) I only started swift ui 2 day ago. Bought mac mini 4 3 day ago to develop ios app but learning mac app first to get experience with mac environment Who can help Contact me via discord alexk3434 I need mac developer friends.
1
0
80
1d
List Cell - Modifying associated object causes reload of whole list
I've got a List containing Colour objects. Each colour may have an associated Project Colour object. What I'm trying to do is set it up so that you can tap a cell and it will add/remove a project colour. The adding/removing is working, but each time I do so, it appears the whole view is reloaded, the scroll position is reset and any predicate is removed. This code I have so far List { ForEach(colourList) { section in let header : String = section.id Section(header: Text(header)) { ForEach(section) { colour in HStack { if checkIfProjectColour(colour: colour) { Image(systemName: "checkmark") } VStack(alignment: .leading){ HStack { if let name = colour.name { Text(name) } } } Spacer() } .contentShape(Rectangle()) .onTapGesture { if checkIfProjectColour(colour: colour) { removeProjectColour(colour: colour) } else { addProjectColour(colour: colour) } } } } } .onAppear() { filters = appSetting.filters colourList.nsPredicate = getFilterPredicate() print("predicate: on appear - \(String(describing: getFilterPredicate()))") } .refreshable { viewContext.refreshAllObjects() } } .searchable(text: $searchText) .onSubmit(of: .search) { colourList.nsPredicate = getFilterPredicate() } .onChange(of: searchText) { colourList.nsPredicate = getFilterPredicate() } The checkIfProjectColour function func checkIfProjectColour(colour : Colour) -> Bool { if let proCols = project.projectColours { for proCol in proCols { let proCol = proCol as! ProjectColour if let col = proCol.colour { if col == colour { return true } } } } return false } and the add/remove functions func addProjectColour(colour : Colour) { let projectColour = ProjectColour(context: viewContext) projectColour.project = project projectColour.colour = colour colour.addToProjectColours(projectColour) project.addToProjectColours(projectColour) do { try viewContext.save() } catch { let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } func removeProjectColour(colour: Colour) { if let proCols = project.projectColours { for proCol in proCols { let proCol = proCol as! ProjectColour if let col = proCol.colour { if col == colour { viewContext.delete(proCol) do { try viewContext.save() } catch { let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } } } } }
2
0
111
2w