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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

iOS 18.1 crash UIHostingView.layoutSubviews() / swift_unknownObjectWeakAssign / objc_storeWeak
We're seeing sporadic crashes on devices running iOS 18.1 - both beta and release builds (22B83). The stack trace is always identical, a snippet of it below. As you can tell from the trace, it's happening in places we embed SwiftUI into UIKit via UIHostingController. Anyone else seeing this? 4 libobjc.A.dylib 0xbe2c _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30 5 libobjc.A.dylib 0xb040 weak_register_no_lock + 396 6 libobjc.A.dylib 0xac50 objc_storeWeak + 472 7 libswiftCore.dylib 0x43ac34 swift_unknownObjectWeakAssign + 24 8 SwiftUI 0xeb74c8 _UIHostingView.base.getter + 160 9 SwiftUI 0x92124 _UIHostingView.layoutSubviews() + 112 10 SwiftUI 0x47860 @objc _UIHostingView.layoutSubviews() + 36
3
0
155
1w
How to draw emojis like the Lock Screen customisation?
On iOS you can create a new Lock Screen that contains a bunch of emoji, and they'll get put on the screen in a repeating pattern, like this: When you have two or more emoji they're placed in alternating patterns, like this: How do I write something like that? I need to handle up to three emoji, and I need the canvas as large as the device's screen, and it needs to be saved as an image. Thanks! (I've already written an emojiToImage() extension on String, but it just plonks one massive emoji in the middle of an image, so I'm doing something wrong there.)
0
0
114
1w
Widget Configuration UI "Add new item"
In the Explore enhancements to App Intents WWDC video at the 11 minute mark I see this UI in the Widget configuration. My question is, how do I configure my Widget to use this UI in the intent configuration? I tried using all different sorts of types and am unable to reproduce it in my app
2
0
137
1w
Xcode 16.1: 'Cannot Preview in This File' Error on macOS After Adding Firebase SDK
Hi, after updating Xcode to Version 16.1, I started a new multiplatform project targeting macOS and iOS. Everything worked fine until I added Firebase SDK 11.4 (using Swift Package Manager). Now, I'm facing an issue where the preview is not possible with "My Mac" after adding Firebase SDK, even with a very simple view like: struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } #Preview { ContentView() } However, previewing with iPhone or iPad works fine. This is really frustrating. When I run the app on a simulator (Mac, iPhone, or iPad), everything works perfectly. The error shown is Cannot preview in this file: Failed to launch [AppName] with the following path: /Users/[myname]/Library/Developer/Xcode/DerivedData/[AppName-gemeoxpjlzrshfifmgmqrkcxdeiz/Build/Products/Debug/FirebaseFirestoreInternal.framework/FirebaseFirestoreInternal Run Destination: macOS 15.1. What I have tried so far: Cleaned the build folder Re-installed Firebase SDK Any insights would be greatly appreciated! Thank you!
0
1
129
1w
PHAssetCollectionChangeRequest.removeAssets Does Not Work
Hello! I am trying to remove a photo from my Photos Library using PhotosUI. I run into this error when I attempt to delete it: "Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)"" No photos access scope requirements declared for changes Failed to log access with error: access= accessor:<> identifier:82068C12-FD10-4DE2-9867-B4406FBFB706 kind:intervalEvent timestampAdjustment:0 visibilityState:0 assetIdentifierCount:0 accessCount:0 tccService:kTCCServicePhotos, error=Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.privacyaccountingd" UserInfo={NSDebugDescription=connection to service named com.apple.privacyaccountingd}
2
0
171
1w
AttributeGraph: AG::Graph::update_main_refs(AG::AttributeID)
Hello, I recently have crashes on my application, it results in many crashes with different reasons, here are the different main reasons: AttributeGraph: AG::Graph::update_main_refs(AG::AttributeID) SwiftUICore: closure #1 in ViewLayoutEngine.explicitAlignment(_:at:) SwiftUICore: __swift_instantiateGenericMetadata My main problem is that these crashes appeared without any major changes to my app, and they never happen when I emulate the app from xcode whether on a simulator or a real device. I have other crashes with other errors I can provide them if necessary. So I have a lot of trouble identifying where the errors come from, I tried to activate zombie objects, and address sanitizer without it revealing anything. Thanks in advance for the answers.
0
0
134
1w
NavigationSplitView issues in iOS 18 and 18.1
Hello, In our current project we are using NavigationSplitView in the following way: var body: some View { NavigationSplitView( sidebar: { ListView() }, detail: { DetailsView() } ) .navigationBarHidden(true) .navigationSplitViewStyle(.automatic) .introspectSplitViewController { splitViewController in splitViewController.preferredDisplayMode = .oneOverSecondary splitViewController.maximumPrimaryColumnWidth = 500 splitViewController.preferredPrimaryColumnWidthFraction = 1 } } } And in iPhone the DetailsView() is pushed using the navigationDestination modifier: .navigationDestination(isPresented: $isShowingDetailsScreen) { DetailsView() .navigationBarHidden(true) } where isShowingDetailsScreen is updated through a button click: Button() { self.isShowingDetailsScreen = true } This works perfectly in iOS versions prior to 18. However starting from this version the button click no longer presents the view desired. Below is what happening in the latest iOS versions: iOS 18: This mechanism is broken altogether, it does not work at all. iOS 18.1: This mechanism is partially broken, when clicking on the button the DetailsView is not presented, however since the page also contains other reactive views, any time one of them is changed through a state change after clicking on that button, the DetailsView is presented. Does anyone faced an issue like this with the new iOS and if so is there any workaround for now? Because this seems to be a bug caused by changes in SwiftUI and shouldn't persist for long.
3
0
258
Sep ’24
Its time for SwiftUI on the web! (WASM, WEBGL)
Hello Apple Community, With a backend development background, I was always reluctant to do any front end. Especially with my bad experience with html & css, my negative opinion towards UI only got stronger. When starting a new project at my current company, I was forced to do SwiftUI for iOS. After a few small (I mean really small) hiccups, I really understood the concept and it all became natural. This positive experience made me want to try other front end frameworks which work for web. I dipped my toes into Jetpack Compose, C# UWP/WPF, Rust with EGUI. I was really impressed with the performance and possibilities of Rust (EGUI) compiled to WASM. I was especially impressed that you do not have to use any HTML or CSS rather the rendering is completely up to you just like with a desktop application. I was always disappointed of the necessity of html, but with the rise of WASM in the recent years, I really hope there will be amazing alternatives using WASM & WEBGL. Rust with EGUI is good and all but lets be honest to our self: With the ease of SwiftUI, its obvious why all the best looking applications are on iOS. Its time for SwiftUI in web. The advantages for the developers are obvious: Arguably better UI Framework No Html DOM stuff Friendlier for new developers One framework & language for multiple platforms etc ... But whats in for Apple? Why "waste" resources? In my opinion the most important thing is: Increased Developer adoption What is your opinion on this topic? Would you use SwiftUI for web? What are you currently using for web? Do you prefer any other frontend framework over SwiftUI? (not considering the platform)
3
8
2.2k
Dec ’22
refreshed/updated data on widgets
Hello, I have a small lightweight macOS application that includes a medium widget but the widget does not update with new data as often as I'd like. I understand that in apple's WidgetKit documentation they mention that apple controls when the widget updates due to battery life concerns, but I'd like to know if theres any way at all to control when the widget updates or when I think it makes sense to do so if I am not able to control how often it refreshes new data. https://github.com/Alexx1105/MacStat-v2.1
2
0
155
1w
Crash After Presenting SwiftUI Alert
I’m seeing a crash in production for a small percentage of users, and have narrowed it down based on logging to happening as or very shortly after an alert is presented using SwiftUI. This seems to be isolated to iOS 17.5.1, but since it’s a low-volume crash I can’t be sure there aren’t other affected versions. What can I understand from the crash report? Here’s a simplified version of the code which presents the alert, which seems so simple I can’t understand why it would crash. And following that is the crash trace. // View (simplified) @MainActor public struct MyView: View { @ObservedObject var model: MyViewModel public init(model: MyViewModel) { self.model = model } public var body: some View { myViewContent .overlay(clearAlert) } var clearAlert: some View { EmptyView().alert( "Are You Sure?", isPresented: $model.isClearAlertVisible, actions: { Button("Keep", role: .cancel) { model.clearAlertKeepButtonWasPressed() } Button("Delete", role: .destructive) { model.clearAlertDeleteButtonWasPressed() } }, message: { Text("This cannot be undone.") } ) } } // Model (simplified) @MainActor public final class MyViewModel: ObservableObject { @Published var isClearAlertVisible = false func clearButtonWasPressed() { isClearAlertVisible = true } func clearAlertKeepButtonWasPressed() { // No-op. } func clearAlertDeleteButtonWasPressed() { // Calls other code. } } Incident Identifier: 36D05FF3-C64E-4327-8589-D8951C8BAFC4 Distributor ID: com.apple.AppStore Hardware Model: iPhone13,2 Process: My App [379] Path: /private/var/containers/Bundle/Application/B589E780-96B2-4A5F-8FCD-8B34F2024595/My App.app/My App Identifier: com.me.MyApp Version: 1.0 (1) AppStoreTools: 15F31e AppVariant: 1:iPhone13,2:15 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: com.me.MyApp [583] Date/Time: 2024-06-21 20:09:20.9767 -0500 Launch Time: 2024-06-20 18:41:01.7542 -0500 OS Version: iPhone OS 17.5.1 (21F90) Release Type: User Baseband Version: 4.50.06 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x00000001a69998c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [379] Triggered by Thread: 0 Kernel Triage: VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter Thread 0 name: Thread 0 Crashed: 0 libswiftCore.dylib 0x00000001a69998c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 AttributeGraph 0x00000001d0cd61a4 Attribute.init<A>(body:value:flags:update:) + 352 (Attribute.swift:473) 2 SwiftUI 0x00000001ac034054 closure #1 in Attribute.init<A>(_:) + 128 (<compiler-generated>:0) 3 SwiftUI 0x00000001ac033cac partial apply for closure #1 in Attribute.init<A>(_:) + 32 (<compiler-generated>:0) 4 libswiftCore.dylib 0x00000001a6ad0450 withUnsafePointer<A, B>(to:_:) + 28 (LifetimeManager.swift:128) 5 SwiftUI 0x00000001ad624d14 closure #2 in UIKitDialogBridge.startTrackingUpdates(actions:) + 268 (UIKitDialogBridge.swift:370) 6 SwiftUI 0x00000001ad624ae0 UIKitDialogBridge.startTrackingUpdates(actions:) + 248 (UIKitDialogBridge.swift:369) 7 SwiftUI 0x00000001ad6250cc closure #4 in UIKitDialogBridge.showNewAlert(_:id:) + 72 (UIKitDialogBridge.swift:471) 8 SwiftUI 0x00000001abfdd050 thunk for @escaping @callee_guaranteed () -> () + 36 (:-1) 9 UIKitCore 0x00000001aa5722e4 -[UIPresentationController transitionDidFinish:] + 1096 (UIPresentationController.m:651) 10 UIKitCore 0x00000001aa571d88 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke.114 + 320 (UIPresentationController.m:1390) 11 UIKitCore 0x00000001aa5cb9ac -[_UIViewControllerTransitionContext completeTransition:] + 116 (UIViewControllerTransitioning.m:304) 12 UIKitCore 0x00000001aa34a91c __UIVIEW_IS_EXECUTING_ANIMATION_COMPLETION_BLOCK__ + 36 (UIView.m:16396) 13 UIKitCore 0x00000001aa34a800 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 624 (UIView.m:16429) 14 UIKitCore 0x00000001aa349518 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 436 (UIView.m:0) 15 UIKitCore 0x00000001aa356b14 -[UIViewAnimationState animationDidStop:finished:] + 192 (UIView.m:2400) 16 UIKitCore 0x00000001aa356b84 -[UIViewAnimationState animationDidStop:finished:] + 304 (UIView.m:2422) 17 QuartzCore 0x00000001a96f8c50 run_animation_callbacks(void*) + 132 (CALayer.mm:7714) 18 libdispatch.dylib 0x00000001aff61dd4 _dispatch_client_callout + 20 (object.m:576) 19 libdispatch.dylib 0x00000001aff705a4 _dispatch_main_queue_drain + 988 (queue.c:7898) 20 libdispatch.dylib 0x00000001aff701b8 _dispatch_main_queue_callback_4CF + 44 (queue.c:8058) 21 CoreFoundation 0x00000001a808f710 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1780) 22 CoreFoundation 0x00000001a808c914 __CFRunLoopRun + 1996 (CFRunLoop.c:3149) 23 CoreFoundation 0x00000001a808bcd8 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420) 24 GraphicsServices 0x00000001ecf3c1a8 GSEventRunModal + 164 (GSEvent.c:2196) 25 UIKitCore 0x00000001aa6c490c -[UIApplication _run] + 888 (UIApplication.m:3713) 26 UIKitCore 0x00000001aa7789d0 UIApplicationMain + 340 (UIApplication.m:5303) 27 SwiftUI 0x00000001ac27c148 closure #1 in KitRendererCommon(_:) + 168 (UIKitApp.swift:51) 28 SwiftUI 0x00000001ac228714 runApp<A>(_:) + 152 (UIKitApp.swift:14) 29 SwiftUI 0x00000001ac2344d0 static App.main() + 132 (App.swift:114) 30 My App 0x00000001001e7bfc static MyApp.$main() + 52 (MyApp.swift:0) 31 My App 0x00000001001e7bfc main + 64 32 dyld 0x00000001cb73de4c start + 2240 (dyldMain.cpp:1298)
3
0
598
Jun ’24
Dynamically change device orientation, and lock to that orientation
I am new to Swift and iOS development. I am trying to wrap a web app where the orientation is dependent on the URL. I have the code working with Stack Overflow as an example where "https://stackoverflow.com" displays in portrait and all other pages change to landscape after being loaded. I have a URL observer that triggers when the URL changes and calls requestGeometryUpdate. I'm running into the following problem: When changing the orientation with requestGeometryUpdate, the orientation changes, but if the device is physically rotated after the change, the orientation changes again. I would like to make the orientation change locked and permanent until a new page is loaded. Any help would be much appreciated. My code is below: import SwiftUI import WebKit struct TestView: View { private let urlString: String = "https://stackoverflow.com/" var body: some View { TestWebView(url: URL(string: urlString)!) .background(Color.black) .scrollIndicators(.hidden) .ignoresSafeArea([.all])//stretchs webview over notch on iphone .defersSystemGestures(on:.bottom)//deprioritizes multitasking indicator .statusBar(hidden: true)//hides time and battery } } class TestController: UIViewController { var webview: WKWebView! var webViewURLObserver: NSKeyValueObservation? override func viewDidLoad() { super.viewDidLoad() let winScene = UIApplication.shared.connectedScenes.first let windowScene = winScene as! UIWindowScene webview = WKWebView(frame: self.view.frame) webview.autoresizingMask = [.flexibleWidth,.flexibleHeight]//makes webview fit screen in portrait and landscape self.view.addSubview(self.webview) webViewURLObserver = self.webview.observe(\.url, options: .new) { webview, change in let url=change.newValue!!;//! converts from optional to string print(url) let arr = url.absoluteString.split(separator: "stackoverflow.com").map(String.init) var portrait=false if(arr.count>1){ let path = arr[1]; if path=="/"{ portrait=true } } if portrait==true { windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .portrait)) { error in print(error)} } else{ windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .landscape)) { error in print(error)} } self.setNeedsUpdateOfSupportedInterfaceOrientations() } } } // WebView Struct struct TestWebView: UIViewControllerRepresentable { let url: URL func makeUIViewController(context: Context) -> TestController { let webviewController = TestController() return webviewController } func updateUIViewController(_ webviewController: TestController, context: Context) { let request = URLRequest(url: url) webviewController.webview.scrollView.contentInsetAdjustmentBehavior = .never webviewController.webview.load(request) } } struct TestView_Previews: PreviewProvider { static var previews: some View { TestView() } }
1
2
1.5k
Nov ’22
VisionOS Set Default Window Size
Is it possible to specify a default window size for a 2D window in visionOS? I know this is normally achieved by modifying the WindowGroup with .defaultSize(width:height:), but I get an error that this was not included in "xrOS". I am able to specify .defaultSize(width:height:depth:) for a volumetric window, but this doesn't have any effect when applied to a 2D one.
11
3
3.8k
Jun ’23
SwiftUI View cannot conform custom Equatable protocol in Swift 6.
In Swift 6, stricter concurrency rules can lead to challenges when making SwiftUI views conform to Equatable. Specifically, the == operator required for Equatable must be nonisolated, which means it cannot access @MainActor-isolated properties. This creates an error when trying to compare views with such properties: Error Example: struct MyView: View, Equatable { let title: String let count: Int static func ==(lhs: MyView, rhs: MyView) -> Bool { // Accessing `title` here would trigger an error due to actor isolation. return lhs.count == rhs.count } var body: some View { Text(title) } } Error Message: Main actor-isolated operator function '==' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode. Any suggestions? Thanks FB: FB15753655 (SwiftUI View cannot conform custom Equatable protocol in Swift 6.)
4
0
152
1w
Inspector List and NavigationSplitView
When using the NavigationSplitView with an inspector containing a list which has swipeActions and onDelete, item actions behave erratically. It seems that there is a gesture conflict between the swipe action and the NavigationSplitView. Is there any modifier that could be used to force gesture focus on the inspector? struct Animal: Hashable { var name : String } struct ContentView: View { @State private var isShowingInspector = false var body: some View { NavigationSplitView { Text("Main") } detail: { Text("Detail") .inspector(isPresented: $isShowingInspector) { InspectorView() .toolbar { ToolbarItem(placement: .primaryAction) { Button { isShowingInspector.toggle() } label: { Label("Preferences", systemImage: "gearshape") } } } } } } } struct InspectorView: View { @State var animals = [ Animal(name: "Dog"), Animal(name: "Cat"), Animal(name: "Parrot") ] @State private var selectedAnimal: Animal? var body: some View { NavigationStack { Text(selectedAnimal?.name ?? "Select an animal") List(selection: $selectedAnimal) { Section { ForEach(animals, id: \.self) { animal in Text(animal.name) .swipeActions(edge: .leading) { Button("Edit") { } .tint(.green) } } .onDelete { indexSet in } } header: { Text("Animals") } } } } }
1
0
112
2w
SwiftUI FormView not updating after value creation/updating in a SubView
I'm developing a SwiftUI, CoreData / CloudKit App with Xcode 16.2 & Sequoia 15.2. The main CoreData entity has 20 NSManaged vars and 5 derived vars, the latter being computed from the managed vars and dependent computed vars - this somewhat akin to a spreadsheet. The data entry/updating Form is complex for each managed var because the user needs to be able to enter data in either Imperial or Metric units, and then switch (by Button) between units for viewing equivalents. This has to happen on an individual managed var basis, because some source data are in Imperial and others Metric. Consequently, I use a generalised SubView on the Form for processing the managed var (passed as a parameter with its identity) and then updating the CoreData Entity (about 100 lines of code in total): i.e. there are 20 uses of the generalised SubView within the Main Form. However, none of the SubViews triggers an update of the managed var in the Form, nor computations of the derived vars. On initial load of the app, the CoreData entity is retrieved and the computations happen correctly: thereafter not. No technique for refreshing either View works: e.g. trigger based on NSManagedObjectContextDidSave; nor does reloading the CoreData entity after Context Save (CoreData doesn't recognise changes at the attribute level anyway). If the SubView is removed and replaced with code within the Form View itself, then it works. However, this will require about 40 @State vars, 20 onCommits, etc - so it's not something I'm keen to do. Below is a much-simplified example of the problem. Form{ Section(header: Text("Test Record")){ Text(testRec.dateString ?? "n/a") TextField("Notes",text:$text) .onSubmit{ testRec.notes = text dataStore.contextSave() } //DoubleNumberEntry(testRec: testRec) - doesn't work TextField("Double",value:$numDbl,format: .number) // This works .onSubmit{ testRec.dblNum = numDbl dataStore.contextSave() } TextField("Integer",value: $numInt,format: .number) .onSubmit{ testRec.intNum = Int16(numInt) dataStore.contextSave() } Text(String(format:"%.2f",testRec.computation)) Section(header: Text("Computations")) { Text(String(format:"%.2f",testRec.computation)) Text(String(format:"%.2f",testRec.anotherComputation)) } } } A much simplified version of my NSManaged var entry/updating. struct DoubleNumberEntry: View { let dataStore = MainController.shared.dataStore var testRec : TestRec @State private var numDbl: Double init(testRec: TestRec) { self.testRec = testRec self.numDbl = testRec.dblNum } var body: some View { TextField("Double",value:$numDbl,format: .number) .onSubmit{ testRec.dblNum = numDbl dataStore.contextSave() } } } I'd appreciate any offered solution or advice. Regards, Michaela
1
0
181
2w
Sheet presentationDetents breaks after rapid open/dismiss cycles
Basic Information Please provide a descriptive title for your feedback: Sheet presentationDetents breaks after rapid open/dismiss cycles Which platform is most relevant for your report? iOS Description Steps to Reproduce: Create a sheet with presentationDetents([.medium]) Rapidly perform these actions multiple times (usually 3-4 times): a. Open the sheet b. Immediately scroll down to dismiss Open the sheet again Observe that the sheet now appears at .large size, ignoring the .medium detent Expected Result: Sheet should consistently maintain .medium size regardless of how quickly it is opened and dismissed. Actual Result: After rapid open/dismiss cycles, the sheet ignores .medium detent and appears at .large size. Reproduction Rate: Occurs consistently after 3-4 rapid open/dismiss cycles More likely to occur with faster open/dismiss actions Configuration: iOS 18 Xcode 16.0 (16A242d) SwiftUI Device: iPhone 14
3
1
208
2w
Visual artifacts in LazyVStack
Some strange visual artifacts appeared in my app after updating Xcode to 16.0. The old version of the app was built with Xcode 15.x and working fine without any visual artifacts, but for the latest release I've used Xcode 16.0 and some strange visual artifacts appeared in LazyVStack on iOS 18.x. https://www.veed.io/view/828ed62c-a8ee-4102-846c-55b28a7f4b74?panel=share Anyone can help me with a fix or workaround ?
2
0
108
2w