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

`NavigationStack` when presented by sheet is forced to be reevaluated when app is in background
Development environment: Xcode 16.1, macOS 15.1 (24B83) OS version: iOS iOS 17.5 and above When NavigationStack is presented by a sheet, and navigationDestination API is being used for navigation within the stack, the sheet content is forced to be reevaluated when app is in background. Sample Project import SwiftUI struct TestView: View { var id: Int @State private var isLoading = false @State private var presentSheet = false var body: some View { let _ = Self._printChanges() VStack { if isLoading { ProgressView() } else { VStack { Text("View: \(id)") Text("Not loading") Button("Present Sheet in NavStack") { presentSheet = true } NavigationLink("Show Link", value: id * 100) } } } .sheet( isPresented: $presentSheet, content: { NavigationStack { TestView(id: self.id + 1) // Comment this block out and note the view no longer reloads when app is in background when there's > 1 sheet modals .navigationDestination(for: Int.self, destination: { num in TestView(id: num) }) } } ) .task { isLoading = true defer { isLoading = false } try? await Task.sleep(for: .seconds(1)) } } } struct ContentView: View { var body: some View { let _ = Self._printChanges() VStack { content .padding() } } var content: some View { VStack { NavigationStack { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) TestView(id: 0) } .navigationDestination(for: Int.self, destination: { num in TestView(id: num) }) } } } } Steps to reproduce: To reproduce the issue in the sample project: Tap on present sheet in navstack button to invoke View #1 presented in sheet Put the app into multitasking mode by tapping on the simulator home button twice Observe that console does not emit debug messages on SwiftUI View change. Also observe that there was no loading in the view Tap on present sheet in navstack button again to invoke View #2 presented in sheet Repeat step #2, but this time observe that console does emit debug message that SwiftUI View were changed due to the following: TestView: @self, @identity, _isLoading, _presentSheet changed. TestView: _isLoading changed. TestView: _isLoading changed. To remove the issue: 7. Comment out the block on navigationDestination. Recompile the app and run it in simulator 8. Repeat step 2-5. Note this time the console does not emit debug message that SwiftUI View were changed.
1
1
111
1w
MacOS SwiftUI: Back button in NavigationSplitView detail view
I have a Split View with the sidebar, content, and detail. Everything is working, but when I select on a NavigationLink in my detail view, the back button is seen next to the title above the content view. I want that back button to be displayed in the top bar on the left side of the detail view. I was expecting it to do this automatically, but I must be missing something. This is where I want it to appear. This is where it appears. I made a simplified version of my code, because it would be too much to post but this has the same behavior. struct TestView: View { enum SidebarSelections { case cycles } @State private var sidebarSelection: SidebarSelections = .cycles var body: some View { NavigationSplitView(sidebar: { List(selection: $sidebarSelection, content: { Label("Cycles", systemImage: "calendar") .tag(SidebarSelections.cycles) }) }, content: { switch sidebarSelection { case .cycles: NavigationStack { List { // Displayed in Content NavigationLink("Cycle link", destination: { // Displayed in the Detail NavigationStack { List { NavigationLink("Detail Link", destination: { Text("More details") }) } } }) } } } }, detail: { ContentUnavailableView("Nothing to see here", systemImage: "cloud") }) } } Is what I want to do possible? Here is a Stack Overflow post that had it working at one point.
2
0
175
2w
DocumentGroup opens an empty document on Mac Catalyst when the "Optimize for Mac" is checked
I am using a Mac Catalyst with SwiftUI for our document-based app with DocumentGroup. The issue is that when we create a new document or open an existing one, the opened view is completely blank. It is only blank/empty when the "Optimzie for Mac" is checked. If it is "Scaled t oMatch iPad", then it works well. Xcode 16.1 macOS 15.1 struct DocumentGroupTestApp: App { var body: some Scene { DocumentGroup(newDocument: WritingAppDocument()) { file in TestView() // it is empty when it gets opened. It does not work if the option "Optimize for Mac" is checked. If it is scale iPad, then it works. } } } struct TestView: View { var body: some View { Text("Hello, World!") } }
2
0
133
1w
fileImporter doesn't do anything on another user's device
Hello, I'm seeing a strange error on another user's device where the SwiftUI file importer doesn't do anything at all. When selecting multiple files and hitting "open", the importer just freezes. Here's a video showing the problem: https://streamable.com/u5grgy I'm unable to replicate on my own device, so I'm not sure what could be going on. I have startAccessingSecurityScopedResource and stopAccessingSecurityResource everywhere I access a file from fileImporter as well.
2
0
93
2w
SwifttData Record Update
Hi When connecting a SwiftData module property to a SwiftUI view such as a text field and the field changes by user the property get updated in the SwiftData database, now suppose I want to run a validation code or delay updates to Database till use click a submit button how to do that ? delay those auto updates if we can name it ? Kind Regards Code Example import SwiftUI import SwiftData struct GListSel2: View { @Bindable var patient: Patient var body: some View { HStack { TextField("Gender", text: $patient.gender) } } }
1
0
108
2w
RealityView Attachments on iOS 18 & Visually Appealing AR Labeling Alternatives
I want use SwiftUI views as RealityKit entities to display AR Labels within a RealityKit scene, and the labels could be more complicated than just text and window as they might include images, dynamic texts, animations, WebViews, etc. Vision OS enables this through RealityView attachments, and there is a RealityView support on iOS 18. Tried running RealityView attachments code samples from VisionOS on iOS 18. However, the code below gives errors on iOS 18: import SwiftUI import RealityKit struct PassportRealityView: View { let qrCodeCenter: SIMD3<Float> let assetID: String var body: some View { RealityView { content, attachments in // Setup your AR content, such as markers or 3D models if let qrAnchor = try? await Entity(named: "QRAnchor") { qrAnchor.position = qrCodeCenter content.add(qrAnchor) } } attachments: { Attachment(id: "passportTextAttachment") { Text(assetID) .font(.title3) .foregroundColor(.white) .background(Color.black.opacity(0.7)) .padding(5) .cornerRadius(5) } } .frame(width: 300, height: 400) } } When I remove "attachments" keyword and the block, the errors are kind of gone. That does not help me as I want to attach SwiftUI views to Anchor Entities in RealityKit. As I understand, RealityView attachments are not supported on iOS 18. I wonder if there is any way of showing SwiftUI views as entities on iOS 18 at this point. Or am I forced to use the text meshes and 3d planes to build the UI? I checked out the RealityUI plugin, but it's too simple for my use case of building complex AR labels. Any advice would be appreciated. Thanks!
0
0
190
2w
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
1d
I am unable to programmatically hide status Bar
PLATFORM AND VERSION iOS Development environment: Xcode 16, macOS 15.0.1 Run-time configuration: iOS 18.1 DESCRIPTION OF THE PROBLEM I am experiencing inconsistent behaviour in SwiftUI when attempting to hide the status bar programmatically. Specifically, I want the status bar to be hidden only during the AreaQuizView, but the behaviour is not persistent across different views. On some views, the status bar hides correctly, while on others, it does not. I am using .statusBarHidden() to achieve this. STEPS TO REPRODUCE In AreasView, apply .statusBarHidden() to the outermost VStack. The status bar hides as expected. In AreaQuizView, apply the same .statusBarHidden() to the outermost stack. However, in this view, the status bar remains visible. In the Build Targets, if I set Status bar is initially hidden to YES in the info.plist, I lose control over the status bar entirely. EXPECTED BEHAVIOUR I would expect that .statusBarHidden() would behave consistently across all views, allowing me to programmatically hide the status bar only during AreaQuizView and leave it visible for other views. ADVICE REQUESTED Could you please advise on how to achieve the desired behaviour, where the status bar is only hidden during AreaQuizView? I would also appreciate any guidance on ensuring consistent behaviour across different views. Please advise.
3
0
173
6d
How to Remove OpaqueTypeErasure from SwiftUI
I am using swiftui lately in my iOS mobile app, The Mobile app already has a pipeline that detect any experimental features and throw an error I am using swift 5 and as you all know SwiftUI is using some of OpaqueTypeErasure utility types like "some" I heard that in swift 6 the OpaqueTypeErasure is not experimental anymore But upgrading the app swift version will be a very long process Also changing the pipeline will be a very long and tiring process So i want to know if there is a way to remove OpaqueTypeErasure from SwiftUI and what is the alternatives for bypassing the error that being thrown from the pipeline
3
0
182
2w
MacOS SwiftUI: Is it impossible to clear a Table selection?
I figured it would be as simple as changing the selection variable back to nil, but that seemingly has no effect. The Table row stays selected, and if I press on it again, it won't trigger my .navigationDestination(). How can I resolve this? I found another post asking the same thing, with no resolution. The only way I can clear it is by clicking with my mouse somewhere else. @State private var selectedID: UUID? = nil Table(tableData, selection: $selectedID, sortOrder: $sortOrder)... .navigationDestination(item: $selectedID, destination: { id in if let cycle = cycles.first(where: {$0.id == id}) { CycleDetailView(cycle: cycle) .onDisappear(perform: { selectedID = nil }) } })
2
0
141
2w
App Crashes on QuartzCore: CA::Layer::layout_if_needed(CA::Transaction*) + 504
I have facing an above crash for many users device running on iOS 17.6.1 mostly on iPad devices. I'm not sure why this happening only in 17.X. In Xcode Organizer unable to see this crash in any devices running on OS 18.x. Our app crashes got spiked due to this. I am unable to fix or reproduce the same. The crash log is not pointing to our app code to find the root cause and fix this issue. Have attached the crash log in this post also the crash log roles have mixed values Background &amp;amp; Foreground. But most of the crash is in background. Is this any crash related to system and that only solved by OS update? I have updated the app using Xcode 16 and 16.1 still facing this crash unable to symbolicate the crash report as well. Any ideas/solution how to solve this or how to proceed further. Have attached the entire crash log below. RoleBackgroundCrash.crash RoleForeGroundCrash.crash
0
0
139
2w
SwiftUI Lists down arrow handling broken
This has been broken for over 5 years now. I see 2 different behaviors in 2 different SwiftUI apps. This makes SwiftUI not ready for prime time apps, but I just have tools right now. The VStack { List } doesn't scroll to the item in a long list. The selection moves to the next item in the list, but can't see it. This is just basic UI functionality of a list. UIListView doesn't have this issue. The NavigationView { List { NavigationLink }} wraps around back to the top of the list when pressing down arrow past the last visible item, but there are plenty more list items to visit.
3
0
177
2w
dismissWindow() doesn't dismantle View
We have discovered that our UIViewRepresentable view isn't being dismantled after its window is dismissed via dismissWindow(). This seems to result in a leak of our custom Coordinator class. Every time the user opens a new window, a new Coordinator is created; if the user then dismisses the window manually, or we dismiss it programmatically, the Coordinator remains in memory with no way to destroy it. Is this expected behavior? How can we be sure to clean up our Coordinator when the view's window is closed? Thanks.
0
0
146
2w
WKWebView crashes after repeated reloads on iOS 18
Hi! I have a rather complicated SwiftUI browser app with a WKWebView. There is an option to reload the website after a configurable amount of time. Starting with iOS 18, the app crashes after repeated reloads. How many reloads that are required depends on the device, sometimes 100, sometimes 1000. Reloading is done via a timer that triggers the following code on the main thread: let request = URLRequest(url: url, cachePolicy: policy) self.parent.webView.load(request) The URL is configurable and cachePolicy can be either .reloadIgnoringLocalAndRemoteCacheData or .useProtocolCachePolicy How the crash affects the device also differs from device to device and from time to time. I have suffered from the following crashtypes: App is killed App is killed and Safari also stops working App is killed and the whole OS is really slow The WKWebView stops loading and hangs at 20%. The device is rebooted My app has an option to disable cache. Cache is disabled by setting cachePolicy to .reloadIgnoringLocalAndRemoteCacheData and by removing all cache in a rather complicated way. Basicly i'm doing something like this: dataStore.removeData(ofTypes: types, modifiedSince: Date.distantPast, completionHandler: nil) if let klazz = NSClassFromString("Web" + "History"), let clazz = klazz as AnyObject as? NSObjectProtocol { if clazz.responds(to: Selector(("optional" + "Shared" + "History"))) { if let webHistory = clazz.perform(Selector(("optional" + "Shared" + "History"))) { let o = webHistory.takeUnretainedValue() _ = o.perform(Selector(("remove" + "All" + "Items"))) } } } if let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first { let contents = (try? FileManager.default.contentsOfDirectory(atPath: cachesPath)) ?? [] for file in contents { if foldersToDelete.contains(file) { let path = cachesPath.appending("/").appending(file) do { try FileManager.default.removeItem(atPath: path) } catch { print("Can't delete cache file: \(path), error: \(error.localizedDescription)") } } } } The cache state affects the intensity of the crash. Disabling the cache shortens the time the app is working, while enabling the cache reduces the intensity of the bug. Based on my investigation, I suspect that loading a website in a WKWebVew leaks memory in iOS 18. If the whole website needs to be requested (= caching off), it results in a more significant memory leak and a faster crash time. Is this a known issue? Am I doing something wrong? Is there a potential workaround?
2
0
248
2w