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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

iOS 18 new ControlWidgetButton custom image/icon/symbol not displayed
Hello, I am trying to create a custom control with the new WidgetKit control widget APIs. In my custom control, I want to display a custom image, in fact a custom symbol. The custom symbol is not displayed with latest iOS 18 Seed 7 (22A5346a). Only system symbols are displayed. I don't find any information about it in the WidgetKit Apple Developer Documentation. ControlWidgetButton(action: MyIntent()){ Label(title: { Text("My Custom Control") }, icon: { Image("mycustomsymbol") //NOT DISPLAYED // Image(systemName: "rectangle.portrait.inset.filled") IS DISPLAYED }) } There was no issue with custom symbols in beta 4. Now since beta 5, custom symbols are not displayed. I wonder if this is a bug or this is intended. Can you help me ? I filed a feedback FB14888220 Thank you
2
2
597
Aug ’24
[Automaker App] Not able to display a keyboard
Hello community, I'm an iOS developer from VW group, I was doing some proof of concepts around an automaker app, and I've found a big blocker. When I was trying to summon a keyboard, it wasn't displayed. So is it even possible? Do I have to do some workaround with Carplay templates in order to be able to have the native keyboard from Carplay, or is there a special component that I need to introduce in my code to summon the keyboard? Thank you very much. David Cosialls.
1
0
116
3w
Pre-initialization of views?
It seems somewhere around the update to xcode 16 and swift 6, apple may have decided to change when view are initialized. My views suddenly pre-initialize before opening the view. Is this a new feature? I have a regular VStack or a LazyVStack, with ForEach and navigationLinks inside. Those views that the navigation link takes you to are initializing as I am scrolling in the VStack. This is absurd, there is so much overhead going on in these views to be initialized. I can think of a fix which is to implement init functions in the onAppear, and keep a property to track if view already appeared. But before that I just want to make sure this is a new feature and not some mishap on my part, and if there is a way to disable it. Thank you.
2
0
118
2w
ShareLink + FileRepresentation: Can't Save to Files
I'm having trouble getting the "Save to Files" option to work with ShareLink. Here's a simple example: struct Item: Transferable {     public static var transferRepresentation: some TransferRepresentation {         FileRepresentation(exportedContentType: .jpeg) { item in // Write a jpeg to disk             let url = URL.documentsDirectory.appending(path: "item.jpeg")             let jpegData = UIImage(named: "testImg")!.jpegData(compressionQuality: 1)!             try! jpegData.write(to: url)             return SentTransferredFile(url)         }     } } struct ContentView: View {     var body: some View {         ShareLink(item: Item(), preview: SharePreview("Test Item"))     } } The ShareSheet presents all of the usual options, but tapping "Save to Files" briefly presents an empty modal before immediately dismissing. The following errors are logged to the console: 2022-09-12 14:19:57.481592-0700 ExportTest[3468:1374472] [NSExtension] Extension request contains input items but the extension point does not specify a set of allowed payload classes. The extension point's NSExtensionContext subclass must implement `+_allowedItemPayloadClasses`. This must return the set of allowed NSExtensionItem payload classes. In future, this request will fail with an error. 2022-09-12 14:19:58.047009-0700 ExportTest[3468:1374472] [ShareSheet] cancelled request - error: The operation couldn’t be completed. Invalid argument Sharing finished with error: Error Domain=NSPOSIXErrorDomain Code=22 "Invalid argument" at SwiftUI/SharingActivityPickerBridge.swift:266 2022-09-12 14:19:58.584374-0700 ExportTest[3468:1379359] [AXRuntimeCommon] AX Lookup problem - errorCode:1100 error:Permission denied portName:'com.apple.iphone.axserver' PID:3472 ( 0   AXRuntime                           0x00000001ca77b024 _AXGetPortFromCache + 932 1   AXRuntime                           0x00000001ca77d1d8 AXUIElementPerformFencedActionWithValue + 772 2   UIKit                               0x00000002258b3284 3CB83860-AA42-3F9A-9B6E-2954BACE3DAC + 778884 3   libdispatch.dylib                   0x0000000105078598 _dispatch_call_block_and_release + 32 4   libdispatch.dylib                   0x000000010507a04c _dispatch_client_callout + 20 5   libdispatch.dylib                   0x00000001050820fc _dispatch_lane_serial_drain + 988 6   libdispatch.dylib                   0x0000000105082e24 _dispatch_lane_invoke + 420 7   libdispatch.dylib                   0x000000010508fcac _dispatch_workloop_worker_thread + 740 8   libsystem_pthread.dylib             0x00000001ed9e8df8 _pthread_wqthread + 288 9   libsystem_pthread.dylib             0x00000001ed9e8b98 start_wqthread + 8 ) Additionally, this error is logged when the ShareSheet is first presented (before tapping Save to Files): [ShareSheet] Couldn't load file URL for Collaboration Item Provider:<NSItemProvider: 0x282a1d650> {types = (     "public.jpeg" )} : (null) Has anybody had luck getting custom Transferable representations to work with ShareLink?
6
2
2.6k
Sep ’22
Identify what is being dragged globally
I would like to implement the same kind of behavior as the Dropoverapp application, specifically being able to perform a specific action when files are dragged (such as opening a window, for example). I have written the code below to capture the mouse coordinates, drag, drop, and click globally. However, I don't know how to determine the nature of what is being dropped. Do you have any ideas on how to detect the nature of what is being dragged outside the application's scope? Here is my current code: import SwiftUI import CoreGraphics struct ContentView: View { @State private var mouseX: CGFloat = 0.0 @State private var mouseY: CGFloat = 0.0 @State private var isClicked: Bool = false @State private var isDragging: Bool = false private var mouseTracker = MouseTracker.shared var body: some View { VStack { Text("Mouse coordinates: \(mouseX, specifier: "%.2f"), \(mouseY, specifier: "%.2f")") .padding() Text(isClicked ? "Mouse is clicked" : "Mouse is not clicked") .padding() Text(isDragging ? "Mouse is dragging" : "Mouse is not dragging") .padding() } .frame(width: 400, height: 200) .onAppear { mouseTracker.startTracking { newMouseX, newMouseY, newIsClicked, newIsDragging in self.mouseX = newMouseX self.mouseY = newMouseY self.isClicked = newIsClicked self.isDragging = newIsDragging } } } } class MouseTracker { static let shared = MouseTracker() private var eventTap: CFMachPort? private var runLoopSource: CFRunLoopSource? private var isClicked: Bool = false private var isDragging: Bool = false private var callback: ((CGFloat, CGFloat, Bool, Bool) -> Void)? func startTracking(callback: @escaping (CGFloat, CGFloat, Bool, Bool) -> Void) { self.callback = callback let mask: CGEventMask = (1 << CGEventType.mouseMoved.rawValue) | (1 << CGEventType.leftMouseDown.rawValue) | (1 << CGEventType.leftMouseUp.rawValue) | (1 << CGEventType.leftMouseDragged.rawValue) // Pass 'self' via 'userInfo' let selfPointer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) guard let eventTap = CGEvent.tapCreate( tap: .cghidEventTap, place: .headInsertEventTap, options: .defaultTap, eventsOfInterest: mask, callback: MouseTracker.mouseEventCallback, userInfo: selfPointer ) else { print("Failed to create event tap") return } self.eventTap = eventTap runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0) CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes) CGEvent.tapEnable(tap: eventTap, enable: true) } // Static callback function private static let mouseEventCallback: CGEventTapCallBack = { _, eventType, event, userInfo in guard let userInfo = userInfo else { return Unmanaged.passUnretained(event) } // Retrieve the instance of MouseTracker from userInfo let tracker = Unmanaged<MouseTracker>.fromOpaque(userInfo).takeUnretainedValue() let location = NSEvent.mouseLocation // Update the click and drag state switch eventType { case .leftMouseDown: tracker.isClicked = true tracker.isDragging = false case .leftMouseUp: tracker.isClicked = false tracker.isDragging = false case .leftMouseDragged: tracker.isDragging = true default: break } // Call the callback on the main thread DispatchQueue.main.async { tracker.callback?(location.x, location.y, tracker.isClicked, tracker.isDragging) } return Unmanaged.passUnretained(event) } }
0
0
116
2w
SwiftUI 'List' performance issue on macOS
Hi, When using SwiftUI ‘List’ with a large number of elements (4000+), I noticed a significant performance issue if extracting the views inside the ‘ForEach’ block into their own subview class. It affects scrolling performance, and using the scroll handle in the scrollbar causes stutters and beachballs. This seems to happen on macOS only ... the same project works fine on iOS. Here's an example of what I mean: List (selection: $multiSelectedContacts) { ForEach(items) { item in // 1. this subview is the problem ... replace it with the contents of the subview, and it works fine PlainContentItemView(item: item) // 2. Uncomment this part for it to work fine (and comment out PlainContentItemView above) /*HStack { if let timestamp = item.timestamp, let itemNumber = item.itemNumber { Text("\(itemNumber) - \(timestamp, formatter: itemFormatter)") } }*/ } } struct PlainContentItemView: View { let item: Item var body: some View { HStack { if let timestamp = item.timestamp, let itemNumber = item.itemNumber { Text("\(itemNumber) - \(timestamp, formatter: itemFormatter)") } } } } Item is a NSManagedObject subclass, and conforms to Identifiable by using the objectID string value. With this, scrolling up and down using the scrolling handle, causes stuttering scrolling and can beachball on my machine (MacBook Pro M1). If I comment out the ‘PlainContentItemView’ and just use the HStack directly (which is what was extracted to ‘PlainContentItemView’), the performance noticeably improves, and I can scroll up and down smoothly. Is this just a bug with SwiftUI, and/or can I do something to improve this?
0
0
164
2w
Preventing Swipe-to-Dismiss on SwiftUI Sheets no longer working in iOS 18.1 (22B83)
The interactiveDismissDisabled() function in SwiftUI's Sheet no longer works as expected in iOS 18.1 (22B83). It was working as expected until iOS 18.0.1. Are there any other users experiencing the same issue? struct ContentView: View { @State private var openSheet = false var body: some View { NavigationStack { Button("Open") { openSheet = true } .sheet(isPresented: $openSheet) { SheetView() } } } } struct SheetView: View { @Environment(\.dismiss) private var dismiss var body: some View { NavigationStack { Text("This is the Sheet") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } } .interactiveDismissDisabled() } } } Supplementary information: In iOS 18.1, even Apple's native Journal app allows users to swipe-to-dismiss the sheet when creating a new entry. Previously, a confirmation dialog would be displayed, but this is no longer the case.​​​​​​​​​​​​​​​​
1
0
167
2w
iOS18.1 Issue SwiftUI’s App
The interactiveDismissDisabled() function in SwiftUI's Sheet no longer works as expected in iOS 18.1 (22B83). It was working as expected until iOS 18.0.1. Are there any other users experiencing the same issue? struct ContentView: View { @State private var openSheet = false var body: some View { NavigationStack { Button("Open") { openSheet = true } .sheet(isPresented: $openSheet) { SheetView() } } } } struct SheetView: View { @Environment(\.dismiss) private var dismiss var body: some View { NavigationStack { Text("This is the Sheet") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } } .interactiveDismissDisabled() } } } Supplementary information: In iOS 18.1, even Apple's native Journal app allows users to swipe-to-dismiss the sheet when creating a new entry. Previously, a confirmation dialog would be displayed, but this is no longer the case.​​​​​​​​​​​​​​​​
2
1
268
2w
Type Eraser for Container
Hi all, Is this allowed: environment(\.container, MyContainer() as Any) While injecting Model container into the environment we use Type . Is there any universal injection type that can inject container as set of any types rather than array similar to navigationPath() type-eraser ?
3
0
142
2w
How would you make a View that magnifies the View(s) beneath it?
I need a magnifying glass function for one of my SwiftUI Views, but can't find a way to implement it as needed. I found a Youtube video where the author renders the view twice, overlaying the second over the first, then scaling and masking it to create the illusion of magnification, but this is expensive and doesn't work in many cases where more complex views are presented (e.g. a LazyVGrid). I've also explored continually capturing partial screenshots and scaling them up to create the illusion of magnification, but there's no straightforward way to achieve this with SwiftUI without getting into the messiness of UIViewRepresentables. Any help would be greatly appreciated
2
0
140
2w
SizeClasses, really?
I have an app with looks at the @Environment(\.horizontalSizeClass) variable and it's mate vertical. On the iPhone 16 sim, if I'm in portrait orientation, It says my vertical class is .regular and horizontal is .compact. If I rotate to landscape, it says vertical is now compact, and horizontal is still compact. That seems inconsistent. I'm trying to wrap my head around designing for size class, how am I supposed to think about this? What I want is two areas of the screen: The main area, which shows a graphic, and a much smaller control and data area, which has a button or two and a very narrow text display, which in my current app counts from 1 to 4. The button area These areas ought never move from where they are, but their contents ought to rotate in place to reflect the orientation. If portrait, the button area is on the bottom, if landscapeLeft, the button are is to the right, if landscapeRight, the button area is to the left. This currently sort of works if I test for the max of height or width from a Geometry Reader, but it doesn't handle landscapeRight or portraitUpsideDown correctly.
1
0
128
2w
I can’t understand this SwiftUI compile error.
Text("Sample Text with wrong font type") .font(.bold) I know this code is incorrect, and it returns an error stating that .font doesn’t have a .bold type. However, when I place this incorrect code within a stack… …no error message appears. Instead, I get: The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions when trying to run the code. It’s unclear why the compiler doesn’t specify that the issue originates from .font(.bold). This was confusing, and I spent 20 minutes figuring out it was a typo.
3
0
184
2w
SwiftUI TabView lifecycle is weird
I tested the life cycle of TabView and its sub-Views through the demo and found something strange. Please help analyze it. Thank you. The demo project is here https://feedbackassistant.apple.com/feedback/15629780 Operation steps: Step 1: launch app Step 2: click Login button the below log is correct SettingsViewModel init HomeViewModel init HomeView appear Step 3: click Settings tab SettingsView appear (correct) Step 4: click Refresh TabView button the below log is incorrect Refresh TabView StatusViewModel init AccountViewModel init StatusViewModel init (weird) AccountViewModel init (weird) HomeView appear (weird) StatusViewModel deinit AccountViewModel deinit AccountView appear SettingsViewModel deinit HomeViewModel deinit Expect log: Refresh TabView SettingsViewModel deinit HomeViewModel deinit StatusViewModel init AccountViewModel init AccountView appear
0
0
148
2w
SwiftUI Previews creating views out of thin air?
My iOS (iPhone/iPad/Mac Catalyst) app has a relatively complex authentication flow, primarily required due to it being an API client. Several of my views have .task modifiers that begin executing code when the views are created. After moving to iOS 18 and Xcode 16, when running in the Simulator, I began noticing my workflow was breaking as views were being created out of sequence... but not by me 🤯 Here is an example stack when I place a breakpoint inside of this view's .task. From my logging (and this stack) I can verify I am not creating this view. This view has no preview associated with it, and there are no previews up the view hierarchy from it either. This happens in the Simulator only The only clue I have to go on is this line of text which is present at the top of what looks like ASM when I click on the (5) line in the stack above. SwiftUI`(1) await resume partial function for dispatch thunk of static SwiftUI.PreviewModifier.makeSharedContext() async throws -> τ_0_0.Context: If this (or any hierarchical view) used Previews, I'd remove them to see if it had an effect, but they don't! I'm at a loss on what to do here...
8
0
213
2w
'Save to Files' doesn't work with ShareLink with FileRepresentation
I want to use ShareLink+FileRepresentation to save a small text file to my iPhone with the steps below. Tap [Share...] to display the share sheet. This sheet contains [Save to Files]. Tap [Save to Files]. A black sheet is displayed, but it disappears instantly. In step 3, I was expecting a browser to be displayed to select the location where the file will be saved. But in fact, a black sheet appears, which quickly disappears. The implemented code is as follows. import SwiftUI @main struct SLSandboxApp: App { var body: some Scene { WindowGroup { let title = Text("File Output") let numListString = "123,456,789" let numListFileName = "numlist.csv" let tagListFile = TextFile(content: numListString, filename: numListFileName) ShareView(title: title, fileToShare: tagListFile, messageToPreview: numListFileName) } } } struct ShareView: View { let title: Text let fileToShare: TextFile let messageToPreview: String var body: some View { ShareLink(item: self.fileToShare, preview: SharePreview(self.messageToPreview)) } } struct TextFile: Transferable { let content: String let filename: String static var transferRepresentation: some TransferRepresentation { FileRepresentation(exportedContentType: .data) { textFile in let data = textFile.content.data(using: .utf8) ?? Data() let tempDirectory = FileManager.default.temporaryDirectory let fileURL = tempDirectory.appendingPathComponent(textFile.filename) try data.write(to: fileURL) return SentTransferredFile(fileURL) } } } The development environment is as follows. Xcode 15.4 (Deployment Target = iOS Deployment Target 17.5) macOS 14.6.1 The execution environment is as follows. iPhone SE Gen3 17.7 The following is a console log from the time the application was launched to the time when the share sheet was displayed by tapping [Share...]. Error acquiring assertion: &lt;Error Domain=RBSServiceErrorDomain Code=1 "(originator doesn't have entitlement com.apple.runningboard.primitiveattribute AND originator doesn't have entitlement com.apple.runningboard.assertions.frontboard AND target is not running or doesn't have entitlement com.apple.runningboard.trustedtarget AND Target not hosted by originator)" UserInfo={NSLocalizedFailureReason=(originator doesn't have entitlement com.apple.runningboard.primitiveattribute AND originator doesn't have entitlement com.apple.runningboard.assertions.frontboard AND target is not running or doesn't have entitlement com.apple.runningboard.trustedtarget AND Target not hosted by originator)}&gt; (501) personaAttributesForPersonaType for type:0 failed with error Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated: failed at lookup with error 159 - Sandbox restriction.} Received port for identifier response: &lt;(null)&gt; with error:Error Domain=RBSServiceErrorDomain Code=1 "Client not entitled" UserInfo={RBSEntitlement=com.apple.runningboard.process-state, NSLocalizedFailureReason=Client not entitled, RBSPermanent=false} elapsedCPUTimeForFrontBoard couldn't generate a task port Received port for identifier response: &lt;(null)&gt; with error:Error Domain=RBSServiceErrorDomain Code=1 "Client not entitled" UserInfo={RBSEntitlement=com.apple.runningboard.process-state, NSLocalizedFailureReason=Client not entitled, RBSPermanent=false} elapsedCPUTimeForFrontBoard couldn't generate a task port Received port for identifier response: &lt;(null)&gt; with error:Error Domain=RBSServiceErrorDomain Code=1 "Client not entitled" UserInfo={RBSEntitlement=com.apple.runningboard.process-state, NSLocalizedFailureReason=Client not entitled, RBSPermanent=false} elapsedCPUTimeForFrontBoard couldn't generate a task port The following is the console log that was written when I tapped [Save to file] on the share sheet. cancelled request - error: The operation couldn’t be completed. Invalid argument What modifications should I make to the code to get the expected result?
0
0
166
2w
MapKit in List Breaks Top/Bottom Bar FadeIn/Out Effect
I've encountered a weird issue with the new Map for iOS 17. In my list, which includes a MapView among other elements, I've observed that with the new initializer, the top and bottom bars are persistently displayed. They don't hide and only appear when scrolling, as they should. This problem doesn't occur with the old, now-deprecated initializer. To illustrate this, I have two screenshots: one with the map enabled and the other with the map disabled, demonstrating the issue. Here is also my new Map code: struct MapListRowView: View { @Binding internal var location: LocationModel @State internal var user: Bool = true private var position: CLLocationCoordinate2D { .init(latitude: location.latitude, longitude: location.longitude) } private var isPad: Bool { UIDevice.current.userInterfaceIdiom == .pad ? true : false } var body: some View { Map(bounds: .init(minimumDistance: 1250)) { if user { UserAnnotation() } Annotation("", coordinate: position) { ZStack { Circle().fill().foregroundColor(.white).padding(1) Image(systemName: "mappin.circle.fill") .resizable() .foregroundColor(.indigo) }.frame(width: 20, height: 20).opacity(user ? .zero : 1.0) } } .frame(height: isPad ? 200 : 100) .cornerRadius(8) .listRowInsets(.init(top: -5, leading: .zero, bottom: -5, trailing: .zero)) .padding(.vertical, 5) .disabled(true) } }
1
0
471
Nov ’23
Issues with List selection in Sequoia (SwiftUI)
In one of my applications I use several List views with Sections. After upgrading to Sequoia I faced the issue, that after selecting an item, the List suddenly scrolls to a different position. Sometimes the selection even gets out of the view, but in every case a double click just went to the wrong item. At one list I found out, that the issue could be solved after changing the data source. I used a computed property, what seems to be a stupid idea. After changing this it now works. Unfortunately there is another List, where this didn't bring the solution. And unfortunately, I cannot reproduce the issue in a code example. One guess of mine is, that it could be related to the fact, that the rows have different heights (because in some are two lines of text and in some are three). And it seems to happen only in very long lists. It worked perfectly in Sonoma. Does anyone face the same issue?
5
0
212
Sep ’24