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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

.redacted(reason:) modifier ignores .minimumScaleFactor?
While working with the Emoji Rangers Sample Code, I noticed that .redacted(reason:) seems to ignore the minimumScaleFactor() modifier - I have reproduced this behaviour with Xcode 16 and Xcode 16.1 beta 2 on iOS and on the Mac: struct ContentView: View { @State private var isRedacted: Bool = false var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") .font(.largeTitle) Toggle("Redacted", isOn: $isRedacted) } .padding() .minimumScaleFactor(0.1) .redacted(reason: isRedacted ? .placeholder : .invalidated) } } As long as the minimumScaleFactor does not kick in, redacted seems to work as expected: But then it does not: I tried changing the order of both modifiers with no effect. Wonder if this is expected and there is a way to make it work so it preserves the scaled down layout or a bug? Filed just in case: FB15270541 (.redacted(reason:) modifier ignores .minimumScaleFactor)
0
0
88
6d
watchOS app crashing on Series 10 - cannot reproduce on Series 8 running same watchOS version
I'm receiving reports from users that my app is crashing immediately after being opened on the Apple Watch Series 10 using watchOS 11. I've updated my personal Apple Watch Series 8 to watchOS 11 and I'm unable to reproduce this crash using the same release build from the App Store. The version currently on the App Store was built using Xcode 15.4 (22622). I'm preparing an update that is built using Xcode 16.0 (23051) and have asked one of the users reporting the crash to try a TestFlight build built using Xcode 16.0 and they are no longer experiencing this crash. As far as I can tell, the only difference between the version on the App Store and the TestFlight build is that it is built with the watchOS 11 SDK included with Xcode 16.0. I don't think any of my app's dependencies (all managed by Swift Package Manager) have been updated in the TestFlight build. I'm attaching a crash report submitted by one of the users. I believe this is a partially symbolicated crash report and have tried opening it in Xcode in an attempt to make it fully symbolicated without success. I've also received a video recording of the app crashing. I'm also not able to see any crashes occurring with an Apple Watch Series 10 in the Xcode Organizer, which leads me to believe this crash may be occurring at the Springboard level. Any help to further diagnose this issue would be much appreciated.
5
0
195
6d
dismissWindow alternative for macOS 13?
Currently for my SwiftUI application i'm using dismissWindow() to close my windows. However, I want to make my app compatible on macOS 13 to enable a wider audience. My current usage of this function is as follows: func reloadContentViewAfterDelete() { @Environment(\.openWindow) var openWindow @Environment(\.dismissWindow) var dismissWindow dismissWindow(id: "content") openWindow(id: "content") }
1
0
110
6d
iOS 18 Control Widget Button won't open app
XCode Version 16.0 (16A242d) iPhone 12 - iOS 18 (22A3354) Macbook Air M1 - Sonoma 14.6.1 I am currently working on building Control Buttons for our app and I have consistently run into the same issue: Unknown NSError The operation couldn’t be completed. (LNActionExecutorErrorDomain error 2018.) This error can be found in the following posts: Apple Developer Forums - Post 1 Apple Developer Forums - Post 2 Apple Developer Forums - Post 3 StackOverflow - Post 4 Github - Post 5 I've tried every single solution recommended within these posts, however nothing has worked successfully so far. Additionally, I've tried the using .widgetUrl() on the Label() within the ControlWidgetButton like so: ControlWidgetButton(action: JournalControlIntent()) { Label("Open App", systemImage: "pencil.line") .widgetURL(URL(string: "app://control/page")) } But this did not work either. Using the recommended approach to open the app as seen here: https://developer.apple.com/documentation/widgetkit/creating-controls-to-perform-actions-across-the-system#Open-your-app-with-a-control simply won't work since we have a Flutter app with deep linking setup. Meaning the only option is launching either a deep link or universal link. Our URL scheme is setup correctly since it's currently working for our iOS Widgets & Shortcuts(which use widgetURL & openURL). In Post 3, the accepted answer mentions that the control file must have the Target Membership with the App and Widget Targets to work. When I try using this solution the build fails without any errors(until you run it in VSCode where there are many errors about Derived Data - Deleting the derived data doesn't fix this error) I'm wondering if I have added the Control Widget to the incorrect folder within my XCode project? Since if you use the approach of creating a Control through XCode(File > New > Target > Widget Extension > "Include Control" > Next) it creates a top level directory in the project similar to a Stickers or Watch extension. My Control Widgets currently reside in the [App] Widgets > Control Buttons > Control Button.swift. It's then added to my main widget definition(App Widget > App_Widget.swift): @main struct App_Widget: WidgetBundle { var body: some Widget { App_Widget() // works App_Widget_One() // works if #available(iOSApplicationExtension 18.0, *) { ControlButtonOne() // does not open app ControlButtonTwo() // does not open app } } } Thank you for your help and time!
1
0
207
1w
Auxiliary window control in Mac SwiftUI & SwiftData app
I've got a Mac Document App using SwiftUI and SwiftData. All is working well with the models editing, etc. There's a feature I need to implement, and can't seem to make it work. From the main window of the app, I need to be able to launch an auxilliary window containing a view-only representation of the model being edited. The required workflow is something like this: Open a document (SwiftData) Select a sub-model of the document Launch the aux window to display the view of the model data (must be in a separate window, because it will be on a different physical display) Continue making edits to the sub-model, as they are reflected in the other window So, below is the closest I've been able to come, and it's still not working at all. What happens with this code: Click on the "Present" button, the encounter-presentation Window opens, but never loads the data model or the view. It's just an empty window. This is the spot in the main view where the auxiliary window will be launched: @State var presenting: Presentation? = nil var presentingThisEncounter: Bool { presenting?.encounter.id == encounter.id } @Environment(\.openWindow) var openWindow ... if presentingThisEncounter { Button(action: { presenting = nil }) { Label("Stop", systemImage: "stop.fill") .padding(.horizontal, 4) } .preference(key: PresentationPreferenceKey.self, value: presenting) } else { Button(action: { presenting = Presentation(encounter: encounter, display: activeDisplay) openWindow(id: "encounter-presentation") }) { Label("Present", systemImage: "play.fill") .padding(.horizontal, 4) } .preference(key: PresentationPreferenceKey.self, value: nil) } Presentation is declared as: class Presentation: Observable, Equatable { Here's the contents of the App, where the DocumentGroup & model is instantiated, and the aux window is managed: @State var presentation: Presentation? var body: some Scene { DocumentGroup(editing: .encounterList, migrationPlan: EncounterListMigrationPlan.self) { ContentView() .onPreferenceChange(PresentationPreferenceKey.self) { self.presentation = $0 } } Window("Presentation", id: "encounter-presentation") { VStack { if let presentation = presentation { PresentingView(presentation: presentation) } } } } And the definition of PresentationPreferenceKey: struct PresentationPreferenceKey: PreferenceKey { static var defaultValue: Presentation? static func reduce(value: inout Presentation?, nextValue: () -> Presentation?) { value = nextValue() } }
1
0
97
1w
Glitchy page transitions with TabView on watchOS
We're trying to implement transitions between TabView pages similar to what the Fitness app does on watchOS. As the user swipes or uses the Digital Crown to move between pages, the large rings gauge in the center transitions smoothly to a toolbar item. The code to implement this transition is described in two places in Apple's documentation: https://developer.apple.com/documentation/watchos-apps/creating-an-intuitive-and-effective-ui-in-watchos-10 (See the section “Provide continuity with persistent elements”) The WWDC23 session "Design and build apps for watchOS 10", around 9:30 However, copying the code from Apple's documentation doesn't give animation as reliable as what we're seeing in the Fitness app. Any slight reversal of motion causes the transition animation to jump back to the starting state. Has anyone else figured out how to replicate what the Fitness app is doing on watchOS? I've included our View implementation below. Debug prints show what's going wrong: the page variable decrements immediately the user moves backward by any amount. But somehow, the Fitness app gets around this problem. How? struct ContentView: View { @Namespace var namespace @State var page = 0 var body: some View { NavigationStack { TabView(selection: $page) { globeView .containerBackground(Color.blue.gradient, for: .tabView) .navigationTitle("One") .matchedGeometryEffect( id: "globe", in: namespace, properties: .frame, isSource: page == 0) .tag(0) Text("Page two") .containerBackground(Color.green.gradient, for: .tabView) .navigationTitle("Two") .tag(1) } .tabViewStyle(.verticalPage) .toolbar { ToolbarItem(placement: .topBarLeading) { globeView .matchedGeometryEffect( id: "globe", in: namespace, properties: .frame, isSource: page == 1) } } } } @ViewBuilder var globeView: some View { Image(systemName: "globe") .resizable() .scaledToFit() } } Thanks for any help! —Chris
0
0
103
1w
Scale contextMenu preview size to containing content
Hi! I have a multi-line string I'd like to display as text in a long-press preview (using .contextMenu). However, text after 3rd or 4th linebreak (\n) gets clipped. The intended effect is to have the minimum preview size that can fit all of the text. Tried .frame(maxWidth: .infinity, maxHeight: .infinity) on Text() but it didn't have any effect. The only modifier that somewhat works is .containerRelativeFrame([.horizontal, .vertical]) but this gives the maximum preview size, instead of minimum. Any suggestions? TIA. struct RedditView: View { @State private var text = "AAAAAAAAAAAAAAAAAAAAAA?\n\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\nCCCCCCCCCCCCCCCCCCCCCCCCCC" var body: some View { Text("Long press this") .frame(width: 300, height: 100) .contentShape(.rect) .border(Color.blue) .contextMenu(menuItems: { Button { // do something } label: { Label { Text("Edit") } icon: { Image(systemName: "pencil") } } }, preview: { Text(text) // .frame(maxWidth: .infinity, maxHeight: .infinity) .multilineTextAlignment(.center) .padding() //.containerRelativeFrame([.horizontal, .vertical]) } ) } }
0
0
92
1w
SwiftUI Table multiple section bug in iPadOS 18 and mac Catalyst
Hi all, Before updating to iPadOS 18, the Table component in SwiftUI worked as expected, allowing multiple selections using the Shift key and mouse clicks. However, after the update, this functionality no longer works on iPadOS 18 and macOS 15 (running with Catalyst). Here’s a simplified version of the code: @State var selections: Set<String> = [] var body: some View { Table(devices, selection: $selections) { // ... } } Is there any workaround for this issue, or has anyone else encountered the same problem? Thanks!
2
0
102
1w
SwiftUI Form (Grouped) with Table
Hi everyone, I’m having an issue with a SwiftUI Table inside a Form in a macOS app. When the Form style is set to .grouped, the Table does not resize to the full width of the Form or Sheet. However, when I switch to a .plain style, it resizes correctly. Here’s a simplified version of my code: Section(header: Text("Header")) { Table(data) { TableColumn("Column 1", value: \.col1) TableColumn("Column 2", value: \.col2) // Add more columns as needed } .frame(height: 100) } } .formStyle(.grouped) // Issue occurs only with this style Has anyone else experienced this? Any workarounds or suggestions would be greatly appreciated! Thanks!
0
0
135
1w
SwiftUI Buttons and onMoveCommand Missing Presses
In tvOS 18 the onMoveCommand is missing the first press after a view is loaded and every time the direction is changed. It also misses the first press on a button after a focus change. This appears to only impact the newer silver remote and not the older black remote or IR remotes. With the code bellow press any direction 3 times and it will only log twice. struct ButtonTest: View { var body: some View { VStack { Button { debugPrint("button 1") } label: { Text("Button 1") } Button { debugPrint("button 2") } label: { Text("Button 2") } Button { debugPrint("button 3") } label: { Text("Button 3") } } .onMoveCommand(perform: { direction in debugPrint("move \(direction)") }) .padding() } }
4
1
132
1w
EKEventStore unable to save events
I have a feature where I need to write some events to the calendar. It's not working saying Calendar is read only. So I tried the sample app from Apple - Repeating lessions and drop in lessions from link below https://developer.apple.com/documentation/eventkit/accessing_calendar_using_eventkit_and_eventkitui Drop in sessions which uses EKEventEditViewController works fine. But when I run Repeating lessions which requires calendar permissions it keeps saying Calendar is read only. I have hit allow on the access permissions alert and also check settings which shows app has required permissions. can someone help why this is the case? if its a Calendar issue where do you set the modifiable permissions for it? How is EKEventEditViewController able to save events if the Calendar is readonly.
0
0
99
1w
Widgets not displaying data when running on iOS 18
When I build my app on Xcode 16 and run it in an iOS 18 simulator The data downloaded in the app will not get to the widget. Same behaviour happens when running on a physical device. If I run the app in a iOS 17.5 simulator the widget gets and displays the data correctly. is there a setting that I need to change that I’ve missed? The app works perfectly on iOS 18 with a build built in Xcode 15.4
4
0
204
1w
CKAsset URLs discarded after backgrounding app in iOS 18
My app uses a temporary singleton to store CKRecords for user profiles, to prevent repeated fetching of profile pics & display usernames during a user's session. Since iOS 18, after leaving the app in the background for an unspecified period of time & reopening it, the app has started to discard the CKAssets in those 'cached' records. The records are still there, & the custom fields such as the display username string is still accessible. However the profile pic assets aren't? This is the code that is displaying the profile picture, could this be something to do with some changes to how CKAssets are given file urls? if postOwnerRecord != nil, let imageAsset = postOwnerRecord!.object(forKey: "profilePicture") as? CKAsset, let photoData = NSData(contentsOf:imageAsset.fileURL!) { if let uiImage = UIImage(data: photoData as Data) { let imageToUse = Image(uiImage: uiImage) Image(uiImage: imageToUse) } } Expected behavior: CKAssets should persist when resuming the app from the background. Actual behavior: CKAssets are discarded when reopening the app, but custom fields are still accessible. Question: Is this related to iOS 18, or am I mishandling how CKAssets are cached or their file URLs? Is there a better approach to caching these assets across app sessions? Any pointers or changes would be appreciated. I've reviewed iOS 18 release notes but didn't find any clear references to changes with CKAsset handling. Any ideas?
1
0
122
1w
Live Activity activityBackgroundTint not using dark mode colour variant
I have defined a colour in the asset catalog of my widget extension. I am using this widget extension for my live activity. This colour has both an ‘Any’ and ‘Dark’ appearance. I am using this colour in the activityBackgroundTint modifier for my main live activity view (the ActivityPreviewViewKind is content, visible on the Lock Screen). In light mode, this works as expected, but in dark mode, the background colour is still the light mode variant. The content within the view changes according to whether the system is in light or dark mode, but the background does not. I want to avoid using just the background modifier instead of activityBackgroundTint, as this does not colour the ‘Allow Live Activities from …’ and ‘Clear’ sections, which is undesirable. I have also tried reading colorScheme from the environment and choosing the light or dark mode colour variant accordingly, but this workaround also doesn’t completely work. If you keep changing from light and dark mode (via the Settings app, not the control centre, for whatever reason), the background colour actually becomes the opposite of the expected value in this case. Is there a workaround that can help me achieve what I want, or am I simply doing something wrong? I have filed a bug report under FB15148099
1
1
111
1w
iOS 18 SwiftUI sheet resizing from page to form presentation sizing
I'm presenting a UIKit view controller from SwiftUI in a sheet using UIViewControllerRepresentable. The size of the sheet is being set to PagePresentationSizing using the new iOS 18 presentationSizing method. When Split View is used and the size class changes from regular to compact, the sheet resizes as expected to fit in the smaller window. When the app returns to full screen and the size class changes back to regular, the sheet is now displayed using FormPresentationSizing instead of PagePresentationSizing. This all worked as expected in iOS 17 with the view controller modalPresentationStyle being specified in the UIViewControllerRepresentable implementation, but the behaviour has now changed with iOS 18. How do I preserve the desired presentation sizing of the sheet? Thanks for any help.
2
0
236
1w
Can't find or decode availabilityDetailedInfo warning when start editing textField
Whenever I start editing TextField or while editing TextField, Xcode shows this worning, and takes a few seconds to show the keyboard. There is no 'availabilityDetailedInfo' in my source code, and I could not find similar errors on the internet. Can't find or decode availabilityDetailedInfo unavailableReasonsHelper: Failed to get or decode availabilityDetailedInfo Can't find or decode reasons unavailableReasonsHelper: Failed to get or decode unavailable reasons as well Can't find or decode availabilityDetailedInfo unavailableReasonsHelper: Failed to get or decode availabilityDetailedInfo Can't find or decode reasons unavailableReasonsHelper: Failed to get or decode unavailable reasons as well
2
1
154
1w