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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

PhotosPickerItem loadTransferable Progress is always indeterminate
I tried several times to use the PhotosPickerItem loadTransferable function with the goal of receiving some progress value especially when loading large video media. However, the Progress object returned by the function has always isIndeterminate == true and so doesn't have any progress value to observe. Is there some way to make it work ? Some configuration I might have overlooked ? Or is it just not working I might have to revert back to the UIKit photo picker because of this
1
1
121
6d
No macro named 'Preview' - error
So I am trying to move an old project from ios16 to ios17... wanted to play around with the new previews, and animations and first error I get is the above. When I create a new project I can use the macro just fine. What is more: when I add a new swiftUI file I get the same error with the #Preview macro. I went through the project and target settings, making sure everything is set to ios17 and Swift5, but can't find any other settings. Cleared the build cache and rebuilt from scratch. Hoping someone else ran onto the same problem and found a solution? Without using #Preview
3
0
1.1k
Jun ’23
containerBackgroundRemovable(false) breaks tinting for the whole widget
I've encountered what appears to be a bug with widget background image tinting in SwiftUI. When using an image in containerBackground(for: .widget) to fill the entire widget, adding the .containerBackgroundRemovable(false) modifier breaks the widget's tinting behavior: The background image becomes permanently tinted, ignoring any widgetAccentedRenderingMode(_ renderingMode: WidgetAccentedRenderingMode?) settings Text elements become tinted even with .widgetAccentable(false) applied Sample code: struct MyWidget: Widget { var body: some WidgetConfiguration { AppIntentConfiguration(kind: "MyWidget", intent: MyWidgetIntent.self, provider: Provider()) { entry in MyWidgetView(entry: entry) .containerBackground(for: .widget) { Image("background") .resizable() .widgetAccentedRenderingMode(.fullColor) .scaledToFill() } } .containerBackgroundRemovable(false) // This causes the issue } } Workaround: I've managed to resolve this by using a ZStack with disabled content margins and passing the widget size through the entry. However, this seems like unintended behavior with the .containerBackgroundRemovable(false) modifier. Has anyone else encountered this issue or found a better solution? Device: iPhone 15 Pro iOS Version: 18.1 Xcode Version: 16.1
0
0
79
6d
Swift Charts: chartScrollTargetBehavior fails to snap to a day unit
I am working on a scrollable chart that displays days on the horizontal axis. As the user scrolls, I always want them to be able to snap to a specific day. I implemented the following steps described in this WWDC23 session to achieve this. I have set the chartScrollTargetBehavior to .valueAligned(matching: DateComponents(hour: 0)) I have set the x value unit on the BarMark to Calendar.Component.day I ended up with the chart code that looks like this: Chart(dates, id: \.self) { date in BarMark( x: .value("Date", date, unit: Calendar.Component.day), y: .value("Number", 1) ) .annotation { Text(date.formatted(.dateTime.day())) .font(.caption2) } } .chartXAxis { AxisMarks(format: .dateTime.day()) } .chartScrollableAxes(.horizontal) .chartScrollTargetBehavior(.valueAligned(matching: DateComponents(hour: 0))) .chartXVisibleDomain(length: fifteenDays) .chartScrollPosition(x: $selection) However, this fails to work reliably. There is often a situation where the chart scroll position lands on, for instance, Oct 20, 11:56 PM, but the chart snaps to Oct 21. I attempted to solve this problem by introducing an intermediate binding between a state value and a chart selection. This binding aims to normalize the selection always to be the first moment of any given date. But this hasn't been successful. private var selectionBinding: Binding<Date> { Binding { Calendar.current.startOfDay(for: selection) } set: { newValue in self.selection = Calendar.current.startOfDay(for: newValue) } } It's also worth mentioning that this issue also exists in Apple's sample project on Swift Charts. How would you approach solving this? How can I find a way to make the chart scroll position blind to time values and only recognize whole days? Here's the minimal reproducible example project for your reference.
0
0
73
6d
Getting error while building the project
Error:App is ambiguous for type lookup in this context code in UnqueHolidayApp import SwiftUI import RealmSwift @main struct UniqueHolidayApp: App { init() { migrateRealmIfNeeded() } var body: some Scene { WindowGroup { ContentView() } } private func migrateRealmIfNeeded() { let config = Realm.Configuration( schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in if oldSchemaVersion < 1 { // Realm will handle changes automatically for simple additions/removals } } ) Realm.Configuration.defaultConfiguration = config } }
0
0
48
6d
Problems when using @Binding on a dynamic array to edit a list (and the items it contains)
I'm running into an issue where, eventually, something goes "wonky" on some detail items won't present the DetailView when they are clicked on. At first, everything is fine, I can edit (and see results reflected in realtime). I can reorder the list, and I can add Detail items to the list. However, after a while, I start seeing the default detail view (Text("Select a detail item to view")) whenever I click on some items. I've not been able to predict where a failure will occur. In the real app I have a persisted JSON document that never seems to get corrupted. And reflects the edits I perform. With this sample app, I can pretty reliably trigger the issue by moving a detail item in the list, and then adding a detail item, but, it will eventually fail without those actions. Am I doing something that's "forbidden"? (You can create a new app and replace the ContentView.swift with the code below to run this and play with it) import SwiftUI struct ContentView: View { @State var main = Main() var body: some View { NavView(main: $main) .onAppear { for index in 1..<11 { main.details.append( Detail( title: "Detail \(index)", description: "Description \(index)")) } } } } struct NavView: View { @Binding var main: Main var body: some View { NavigationSplitView { ListView(main: $main) } detail: { Text("Select a detail item to view") } } } struct ListView: View { @Binding var main: Main @State private var addedDetailCount = 0 var body: some View { List($main.details, editActions: .move) { $detail in NavigationLink(destination: DetailView(detail: $detail)) { Text("\(detail.title)") } } .toolbar { Button( LocalizedStringKey("Add Detail"), systemImage: "plus" ) { addedDetailCount += 1 main.details.append( .init(title: "new Detail \(addedDetailCount)", description: "description")) } } } } struct DetailView: View { @Binding var detail: Detail var body: some View { Form { Text("id: \(detail.id)") TextField("Title", text: $detail.title) TextField("Detail", text: $detail.description) } .padding() } } struct Main { var details = [Detail]() } struct Detail: Identifiable { var id = UUID() var title: String var description: String } #Preview { ContentView() }
3
0
162
1w
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
176
2w
Sharelink in WatchOS and Messages App
I’m relatively new to SwiftUI, so I’ve got a pretty basic question here. In my watchOS app, I’m using ShareLink to share a string of text to the Mail and Messages apps. Mail shows up in the ShareLink sheet just fine, but Messages doesn’t appear. What’s odd is that when I run the app in Xcode’s preview or in the Simulator, Messages does show up as a sharing option… So now I’m wondering if this is just a quirk with my device or if Apple doesn’t actually support sharing text to Messages from third-party watchOS apps yet? I know some Apple Watch apps (like Contacts) do support sending text/files to Messages, so I’m curious if anyone’s had a similar experience or knows more about this. Any insights would be super helpful!
1
0
87
1w
“Search Bar Overlapping Keyboard and Displaying Suggestions Incorrectly on iPhone 16 Pro”
I’m experiencing an issue with the search bar on my iPhone 16 Pro. When I start typing in the search bar (as shown in the screenshot), the keyboard overlaps with the search suggestions, making it hard to see the contacts and apps that are displayed. The interface seems cluttered, and it becomes difficult to accurately tap on the desired suggestion or contact. Steps to Reproduce: 1. Swipe down to access the search bar on the iPhone 16 Pro. 2. Type a few letters to bring up suggestions for apps, contacts, and messages. Expected Result: The search results should display clearly above the keyboard without overlapping or cluttered suggestions. Actual Result: The keyboard overlaps with the search results, making it difficult to view or select items accurately. Device and OS Details: • iPhone 16 Pro • iOS Version (please replace with your specific version) Has anyone else encountered this issue? Any insights on possible fixes or settings adjustments would be appreciated.
0
0
120
1w
How to resolve SwiftUI.DynamicProperty on MainActor compiler warning on 6.0?
Hi! I'm running into a warning from a SwiftUI.DynamicProperty on a 6.0 development build (swift-6.0-DEVELOPMENT-SNAPSHOT-2024-03-26-a). I am attempting to build a type (conforming to DynamicProperty) that should also be MainActor. This type with also need a custom update function. Here is a simple custom wrapper (handwaving over the orthogonal missing pieces) that shows the warning: import SwiftUI @MainActor struct MainProperty: DynamicProperty { // Main actor-isolated instance method 'update()' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode @MainActor func update() { } } Is there anything I can do about that warning? Does the warning correctly imply that this will be a legit compiler error when 6.0 ships? I can find (at least) two examples of types adopting DynamicProperty from Apple that are also MainActor: FetchRequest and SectionedFetchRequest. What is confusing is that both FetchRequest^1 and SectionedFetchRequest^2 explicitly declare their update method to be MainActor. Is there anything missing from my Wrapper declaration that can get me what I'm looking for? Any more advice about that? Thanks!
4
0
748
Apr ’24
NO ANIMATIONS in NavigationStack or NavigationSplitView
I'm building a macOS app using SwiftUI and I recently updated to xcode 14.3. Since then I've been debugging why none of my animations were working, it turned out that the NavigationSplitView or NavigationStack are somehow interfering with all the animations from withAnimation to .transition() and everything in between. Is anyone else experiencing this, knows a work around or knows why this is happening?
11
9
7.1k
Apr ’23
Control gallery preview bug
Environment: Xcode16, iOS 18.1 official version Background: I created a control center widget using a custom sf symbol Phenomenon: When I first installed it, it displayed normally in the control gallery, but when I recompiled and installed it again, the icon disappeared when I looked at it again in the control gallery. I used Console to check the error log and found that its output was' No image named 'my_custom _symbol_name' found in asset catalog for/private/var/containers/Bundle/Application/F977FCFB-DA1C-4924-8613-50531CA2A364/MyDemoApp. app/PlugIns/MyDemoApp Extension. apex '. I found that this uuid was not consistent with the uuid I print during debugging, as if the control gallery had done some kind of caching; Additionally, when I added my Control to the Control Center, it was able to display normally, and the only issue was with the Control Gallery Attempted method: -Using the system SF Symbol, it works fine and can be displayed normally in the control gallery after recompilation. However, once I switch another SF Symbols, the icons in the control gallery do not update after recompilation and installation -Restarting the device, the same issue still persists Is this a system bug or did I make a mistake? Looking forward to someone helping, thank you My Code: @available(iOSApplicationExtension 18.0, *) struct MySearchControlWidget: ControlWidget { let kind = "MySearchControlWidget" let title = "My Title" var body: some ControlWidgetConfiguration { let intent = MyCommonButtonControlWidgetIntent() StaticControlConfiguration(kind: kind) { ControlWidgetButton(action: intent) { Label("\(title)", image:"my_custom_symbol_name") } } .displayName("\(title)") } }
1
0
99
1w
Use @AppStorage with Arrays
Hey, I know you can write @AppStorage("username") var username: String = "Anonymous" to access a Value, stored In the User Defaults, and you can also overwrite him by changing the value of username. I was wondering if there is any workaround to use @AppStorage with Arrays. Because I don't find anything, but I have a lot of situations where I would use it. Thanks! Max
1
1
882
Dec ’21
HStack required to get columns in a Grid
I've looked at lots of Grid examples. I've seen it documented that views within a GridRow are treated as if they were in an HStack. That's not happening for me. I have to explicitly put them into an HStack or they are treated as new rows. Here's my code: @State private var gridRows : Int = 4 @State private var gridCols : Int = 2 @State private var myItems : [Int] = Array(0...8) var body: some View { Group { if myItems.count > 0 { ScrollView([.vertical]) { Grid(alignment: .leading) { ForEach(0..<gridRows, id: \.self) { rowNdx in GridRow { HStack // <<--- { ForEach(0..<gridCols, id: \.self) { colNdx in Text("\(rowNdx) \(colNdx)") } } } } } } } } } With the HStack I get (as expected). 0 0 0 1 1 0 1 1 2 0 2 1 3 0 3 1 Without the HStack I get 0 0 0 1 1 0 1 1 ... What have I done wrong?
2
0
133
1w
`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
112
2w
Issues with FocusState in List with views containing Textfields
We are having issues with implementing a List that has Views in it that contain a Textfield. The criteria we are trying to achieve is Select to edit the quantity of a product Auto focus on the row with that textfield, with the textfield's contents selected Display/Dismiss the keyboard Mask other rows in the list while interacting with a qty field We explored many routes and are looking for direction on what the designated approach is. This originally was a Tech Support Incident, and I was instructed to post here. There were 2 working project examples available if needed. In an implementation that has the FocusState on the parent view, we see collisions in animation / weird jumpiness // MARK: - Constant enum Constant { static let logTag = "AddReplenishmentProductView" } @Binding var state: ContentViewState // MARK: - Private Properties @State private var focusedLineItemId: String? // MARK: - Life cycle var body: some View { VStack { replenishmentProductList } .background(.tertiary) .navigationTitle("Add Products") .navigationBarTitleDisplayMode(.inline) .toolbarBackground(.visible, for: .navigationBar) } // MARK: - Private Computed properties @ViewBuilder private var replenishmentProductList: some View { ScrollViewReader { proxy in List { let list = Array(state.lineItems.enumerated()) ForEach(list, id: \.1.product.id) { (index, lineItem) in RowView( lineItem: $state.lineItems[index], focusedLineItemId: $focusedLineItemId ) .id(lineItem.id.uuidString) .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) .alignmentGuide(.listRowSeparatorLeading) { _ in return 0 } //  Blocks all the other rows that we are not focusing on. .maskingOverlay(focusId: $focusedLineItemId, elementId: "\(lineItem.id)") } .listSectionSeparator(.hidden) } .listStyle(.plain) .scrollDismissesKeyboard(.never) .scrollContentBackground(.hidden) /*  We are looking for a solution that doesn't require us to have this onChange modifier whenever we want to change a focus. */ .onChange(of: focusedLineItemId) { guard let lineItemId = focusedLineItemId else { return } /*  We need to scroll to a whole RowView so we can see both done and cancel buttons. Without this, the focus will auto-scroll only to the text field, due to updating FocusState. We are experiencing weird jumping issues. It feels like the animations for focus on text field and RowView are clashing between each other. To fix this, we added a delay to the scroll so the focus animation completes first and then we scroll to the RowView. However, when we attempt to focus on a row that is partially shown, sometimes the RowView won't update it's focus and won't focus ultimately on the TextField until we scroll. */ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { withAnimation { //  We need to add the withAnimation call to animate the scroll to the whole row. proxy.scrollTo(lineItemId, anchor: .top) } } } } } } In an implementation where the FocusState is on the row views, we see issues with actually being able to focus. When quantity field we tap is located on a row near the top/bottom of the screen it does not look to be identified correctly, and the ability to scrollTo / the keyboard being presented are broken. struct ContentView: View { // MARK: - Constant enum Constant { static let logTag = "AddReplenishmentProductView" } @Binding var state: ContentViewState // MARK: - Private Properties @State private var focusedLineItemId: String? @FocusState private var focus: String? // MARK: - Life cycle var body: some View { VStack { replenishmentProductList } .background(.tertiary) .navigationTitle("Add Products") .navigationBarTitleDisplayMode(.inline) .toolbarBackground(.visible, for: .navigationBar) } // MARK: - Private Computed properties @ViewBuilder private var replenishmentProductList: some View { ScrollViewReader { proxy in List { let list = Array(state.lineItems.enumerated()) ForEach(list, id: \.1.product.id) { (index, lineItem) in RowView( lineItem: $state.lineItems[index], focusedLineItemId: $focusedLineItemId, focus: $focus ) .id(lineItem.id.uuidString) .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) .alignmentGuide(.listRowSeparatorLeading) { _ in return 0 } //  Blocks all the other rows that we are not focusing on. .maskingOverlay(focusId: $focusedLineItemId, elementId: "\(lineItem.id)") } .listSectionSeparator(.hidden) } .listStyle(.plain) .scrollDismissesKeyboard(.never) .scrollContentBackground(.hidden) /*  We are looking for a solution that doesn't require us to have this onChange modifier whenever we want to change a focus. */ .onChange(of: focusedLineItemId) { /*  We need to scroll to a whole RowView so we can see both done and cancel buttons. Without this, the focus will auto-scroll only to the text field, due to updating FocusState. However, we are experiencing weird jumping issues. It feels like the animations for focus on text field and RowView are clashing between each other. */ focus = focusedLineItemId guard let lineItemId = focusedLineItemId else { return } withAnimation { //  We need to add the withAnimation call to animate the scroll to the whole row. proxy.scrollTo(lineItemId, anchor: .top) } } } } }
4
0
140
2w
How to use ManagedAppDistribution Framework
Hi I have tried the code given on link https://developer.apple.com/documentation/appdistribution/fetching-and-displaying-managed-apps. This code is not compilable in Xcode 16.1. After some fixes i am able to run the code but i am getting Error registering for message: [App catalog changed]: An unspecified, unrecoverable error occurred. Kindly help me with this.
2
0
142
1w