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

SwiftUI Documentation

Posts under SwiftUI subtopic

Post

Replies

Boosts

Views

Activity

Push To Start Live Activity Token Acquisition Issue When Not Attached to Debugger
We are adding a live activity to our app that is started by a push to start live activity token that we supply to our server backend. In the app I have a Task that is retrieving pushToStartTokens from the asynchronous stream provided by the Apple API It looks similar to: // Iterate the async stream from the system for await tokenData in try await Activity<MyActivityAttributes>.pushToStartTokenUpdates { let tokenString = tokenData.map { String(format: "%02x", $0) }.joined() logger.log("Received push start token: \(tokenString, privacy: .public)") } } catch { logger.error("Failed to monitor push start tokens: \(error.localizedDescription, privacy: .public)") } When my app is launched from Xcode and connected via the debugger this code vends a pushToStartToken reliably. However if I run this same code by directly launching the app by tapping the icon on the phone, it almost never vends a pushToStartToken. It only occasionally works. I've tried a variation on the code where instead of always executing the asynchronous stream to obtain the token it first checks for the existence of a pushToStartToken using the this synchronous check prior to entering the for await if let pushStartTokenSync = Activity<AttributeType>.pushToStartToken { let tokenStr = pushStartToekSync.map { String(format: "%02x", $0) }.joined() nextPushToStartToken = pushStartTokenSync logger..log("**** Queried PushToStart Token: \(tokenStr, privacy: .public) ***") } else { logger..log("**** Queried PushToStart Token is nil! ***") } This works more reliably than just falling directly into the stream but I still see many instances where the result is nil. I'm trying to understand what is the correct way to obtain and manage the pushToStartTokens so that getting one is as reliable as possible especially in production builds. When I do get a token, should I persist it somewhere and use that (even across different app executions) until a new one is vended? Appreciate hearing ideas, thoughts and any code samples that illustrate a good management scheme Thank, You. Rob S.
0
0
42
2w
Clarification on safeAreaBar
I've been testing the safeAreaBar modifier to develop a custom tab bar. From my understanding, this should enable the .scrollEdgeEffectStyle to work with this bar, but I don't see any effect. Could you please clarify the difference between safeAreaBar and safeAreaInset?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2
2
81
3w
TipKit popover inside ForEach Loop
I've encountered a problem when placing a tip on an element in a ForEach loop. As long as there is only one element in the list the tip will be shown. But if there are more than one element the tip does not appear on iOS and iPadOS. How do I get the tip to be displayed when several elements are displayed? Is it allowed to use the popoverTip() modifier in a ForEach loop or should it be avoided? Interestingly, it works if you run the attached sample code on macOS. Then the tip is displayed on the “Third” element. import SwiftUI import TipKit struct ContentView: View { private var elements: [String] = ["First", "Second", "Third"] let tip = DemoTip() var body: some View { NavigationStack { List { Section { ForEach(elements, id: \.self) { element in Text(element) .popoverTip(tip) } } } } } } struct DemoTip: Tip { var title: Text { Text("Demo Tip") } } @main struct TipKitTestApp: App { init() { #if DEBUG Tips.showAllTipsForTesting() #endif try? Tips.configure([.displayFrequency(.immediate)]) } var body: some Scene { WindowGroup { ContentView() } } }
3
0
46
3w
Placemark Deprecated
"Use location, address and addressRepresentations instead" Is it possible to know what kind of "Address" a MapItem is representing (State, County, Neighborhood etc) after a MKGeocodingRequest? Is it possible to find out the CLRegion or similar of an map item. (Now when we cannot read it from the Placemark)
1
0
43
3w
SwiftUI Transaction completion handler is being called unexpectedly
Unexpected SwiftUI Transaction Behavior This minimal example demonstrates an unexpected behavior in SwiftUI's Transaction API: var transaction = Transaction(animation: .none) transaction.addAnimationCompletion { print("This should not be called!") } The Issue The completion handler is called immediately after creation, even though the transaction was never used in any SwiftUI animation context (like withTransaction or other animation-related APIs). Expected vs Actual Behavior Expected: The completion handler should only be called after the transaction is actually used in a SwiftUI animation. Actual: The completion handler is called right after creation, regardless of whether the transaction is used or not. Current Workaround To avoid this, I'm forced to implement defensive programming: only creating transactions with completion handlers at the exact moment they're going to be used. This adds unnecessary complexity and goes against the intuitive usage of the Transactions API.
2
0
55
3w
tabViewBottomAccessory inline functionality missing?
Summary As presented in the SwiftUI WWDC video, the new tabViewBottomAccessory should allow for unique contents for .inline. This is what was presented as being used for the Apple Music miniplayer. However, the functionality seems to be either missing or unintuitive. As seen in the photos attached, not only does .inline functionality not seem to do anything, but the inline accessory also has misaligned elements that cannot be fixed by conditionally modifying the contents. Build Target iOS 26.0 Details This problem recurs on physical devices, simulators, and Xcode previews. Here is a view I've constructed for use as a tabViewBottomAccessory: struct FitnessToolbarAccessory: View { @Environment(\.tabViewBottomAccessoryPlacement) var placement var body: some View { if (placement == .inline) { Text("hello") } else { HStack { HStack { Image(systemName: "dumbbell.fill") VStack(alignment: .leading) { Text("Active Workout") Text("Push Day - Chest") .font(.system(size: 13)) } Spacer() Image(systemName: "pause.fill") } .padding() } } } } Here is the result, working as expected in expanded mode: And here is the result in inline mode after minimizing the tabViewBottomAccessory: The content of this inline accessory is clearly incorrect, as it was specified to contain a Text view containing "hello". Additionally, the contents seem to have some incorrect alignment. This occurs regardless of the contents of the accessory, even plain text.
1
0
80
3w
Replacement for ToolbarItems with .bottomBar placement in iOS 26 TabView?
Prior to iOS 26, ToolbarItems with .bottomBar placement were convenient for tab-specific frequent actions. With iOS 26’s new tab layering now obscuring such ToolbarItems, it’s unclear whether .tabViewBottomAccessory is the intended replacement or if another pattern (like persistent floating buttons) is encouraged instead. What’s the recommended way to support quick, tab-specific actions under the new system? I’ve tried conditionally rendering a .tabViewBottomAccessory based on the active tab, but this causes a crash, which I’ve reported as FB18479195.
3
1
209
3w
Crash when conditionally rendering .tabViewBottomAccessory with TabView(selection:) in SwiftUI on iOS 26
Summary When using .tabViewBottomAccessory in SwiftUI and conditionally rendering it based on the selected tab, the app crashes with a NSInternalInconsistencyException related to _bottomAccessory.displayStyle. Steps to Reproduce Create a SwiftUI TabView using a @SceneStorage selectedTab binding. Render a .tabViewBottomAccessory with conditional visibility tied to selectedTab == .storage. Switch between tabs. Return to the tab that conditionally shows the accessory (e.g., “Storage”). Expected Behavior SwiftUI should correctly add, remove, or show/hide the bottom accessory view without crashing. Actual Behavior The app crashes with the following error: Environment iOS version: iOS 26 seed 2 (23A5276f) Xcode: 26 Swift: 6.2 Device: iPhone 12 Pro I have opened a bug report with the FB number: FB18479195 Code Sample import SwiftUI struct ContentView: View { enum TabContent: String { case storage case recipe case profile case addItem } @SceneStorage("selectedTab") private var selectedTab: TabContent = .storage var body: some View { TabView(selection: $selectedTab) { Tab( "Storage", systemImage: "refrigerator", value: TabContent.storage ) { StorageView() } Tab( "Cook", systemImage: "frying.pan", value: TabContent.recipe ) { RecipeView() } Tab( "Profile", systemImage: "person", value: TabContent.profile ) { ProfileView() } } .tabBarMinimizeBehavior(.onScrollDown) .tabViewBottomAccessory { if selectedTab == .storage { Button(action: { }) { Label("Add Item", systemImage: "plus") } } } } }
3
0
218
3w
How can I have a view cover the status bar?
I've been researching everywhere I can, and I have found nothing. I am trying to find a way so that my alert that occurs within my app can drop down but cover the status bar elements (wifi, time, etc). I'm at a loss and was curious if anyone knew how.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
75
3w
SwiftUI: scrollEdgeEffectStyle(.hard, for: .all) bug with preferredColorScheme(.dark)
In the small example below, I have set .preferredColorScheme(.dark). I am pushing a view that has a List. I have a custom background color. When .scrollEdgeEffectStyle(.hard, for: .all) is used, the pushed view top and bottom safe areas flash black before being replaced by the blue background color. If I change this to .scrollEdgeEffectStyle(.soft, for: .all), the issue goes away. If I do not set preferredColorScheme(.dark), the issue also goes away. I filled FB18465023, but wonder if I am just doing something wrong? Video of sample running: https://www.youtube.com/shorts/87rWqHtdmKw. var body: some View { NavigationStack { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") NavigationLink("Push New View") { PushedView() } .buttonStyle(.glass) .padding() } .frame(maxWidth: .infinity, maxHeight: .infinity) .ignoresSafeArea(.all) .background(.blue) } .preferredColorScheme(.dark) } } struct PushedView: View { @State private var searchText = "" var body: some View { List { ForEach(1...30, id: \.self) { index in Label("Label \(index)", systemImage: "number.circle") .listRowBackground(Color.blue) } } // This causes the top and bottom safe areas to start off black before // getting the blue background from below .scrollEdgeEffectStyle(.hard, for: .all) // This does not have the issue // .scrollEdgeEffectStyle(.hard, for: .all) .listStyle(.plain) .background(.blue) .searchable(text: $searchText, prompt: "Search labels...") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Toolbar Button", systemImage: "questionmark") { print("touched") } } } } }
Topic: UI Frameworks SubTopic: SwiftUI
1
0
191
3w
Map Switcher MapKit iOS 14 and up
Hello everyone, I have just started coding using swift and I´m currently building an app that ist using MapKit. It is required to run on iOS 14 and newer and I want to add a Map switcher to switch between the Map Views Standard, Satellite, Hybrid and eventually also OSM. However this apparently is not as straight forward as it seems and I just don't get it to work. I had multiple attempts such as these two, each interface with a separate MapSwitcherView that open on the press of a button: var body: some View { ZStack(alignment: .bottomTrailing) { Group { if selectedMapStyle == .openStreetMap { openStreetMapView() } else { MapContainer(region: $locationManager.region, tracking: $tracking, style: selectedMapStyle) } } .id(selectedMapStyle) .onChange(of: selectedMapStyle) { newStyle in print("Style changed to: (newStyle)") } and Group { switch selectedMapStyle { case .standard: Map(coordinateRegion: $locationManager.region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking) .id("standard") case .satellite: Map(coordinateRegion: $locationManager.region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking) .id("satellite") case .hybrid: Map(coordinateRegion: $locationManager.region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking) .id("hybrid") case .openStreetMap: openStreetMapView() } } Unfortunately the map just doesn't switch. Do you have any suggestions? Should I post some more code of the MapSwitcher or something? Thanks and best regards
4
0
82
3w
How can I build a custom `PickerStyle` in SwiftUI?
I am trying to create a radio group picker in SwiftUI, similar to this: https://www.neobrutalism.dev/docs/radio-group I already have a working view based version here: https://github.com/rational-kunal/NeoBrutalism/blob/main/Sources/NeoBrutalism/Components/Radio/Radio.swift Now I want to replace it with a more concise/swifty way of Picker with PickerStyle API: However, I can't find any official documentation or examples showing how to implement PickerStyle. Is it possible to create my own PickerStyle? If not, what’s the recommended alternative to achieve a radio‑group look while still using Picker? struct NBRadioGroupPickerStyle: PickerStyle { static func _makeView<SelectionValue>(value: _GraphValue<_PickerValue<NBRadioGroupPickerStyle, SelectionValue>>, inputs: _ViewInputs) -> _ViewOutputs where SelectionValue : Hashable { <#code#> } static func _makeViewList<SelectionValue>(value: _GraphValue<_PickerValue<NBRadioGroupPickerStyle, SelectionValue>>, inputs: _ViewListInputs) -> _ViewListOutputs where SelectionValue : Hashable { <#code#> } } Crossposting: https://forums.swift.org/t/how-can-i-build-a-custom-pickerstyle-in-swiftui/80755
0
0
165
3w
Cannot publish iMessage app under sticker category
I have a LIVE imessage sticker app with simple UI that is auto installed under the sticker section. And i am trying to rewrite the app but the new app, when testing, always publish under the imessage app category instead of under the sticker category. here is the live app on app store: https://apps.apple.com/us/app/qoobee-agapi-stickers/id1176590163 Does anyone know how to get my imessage app published under the sticker category?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
43
3w
What is causing the Freeze in this SwiftUI View?
I made a small project that freezes after the following steps: Run the app Turn on VoiceOver Tap on "Header" once so it is read out loud Turn off VoiceOver Scroll up and down really quickly Using the Time Profiler, the items in the Main Thread followed by significant drops are: 19.11 s 85.1% 0 s closure #2 in closure #1 in ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) 13.05 s 58.1% 4.00 ms ViewGraph.updateOutputs(async:) 7.97 s 35.5% 83.00 ms AG::Graph::UpdateStack::update() 5.76 s 25.6% 19.00 ms LayoutScrollableTransform.updateValue() 1.73 s  7.7% 2.00 ms specialized NativeDictionary.setValue(:forKey:isUnique:) 579.00 ms  2.6% 58.00 ms 0x100a8c908 311.00 ms  1.4% 165.00 ms __thread_stack_pcs I see the memory usage increase by about 0.6 MB per second while frozen. And there are a few things that prevent the freeze: Changing LazyVStack for VStack Removing the VStack from the Section Removing the header: parameter from the Section Reducing the range of the ForEach Move the Text(verbatim: "Text at same level as ForEach containing Section") outside of the LazyVStack However, these are all things I need to keep for my actual app. So what is causing this hang? Am I using SwiftUI in any way it's not intended to be used? import SwiftUI struct ContentView: View { var body: some View { VStack { VStack(alignment: .leading) { Image(systemName: "pencil.circle.fill") Text("Title") Text("Label") } ScrollView { LazyVStack { Section { VStack { ForEach(0..<70) { _ in Text(verbatim: "A") } } } header: { Text(verbatim: "Header") } Text(verbatim: "Text at same level as ForEach containing Section") } } } } } AppDelegate: @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = UINavigationController(rootViewController: MainViewController()) window.makeKeyAndVisible() self.window = window return true } } MainViewController: import UIKit import SwiftUI final class MainViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let swiftUIView = ContentView() let hostingController = UIHostingController(rootView: swiftUIView) addChild(hostingController) hostingController.view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(hostingController.view) NSLayoutConstraint.activate([ hostingController.view.topAnchor.constraint(equalTo: view.topAnchor), hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) hostingController.didMove(toParent: self) view.backgroundColor = .white } }
1
0
70
3w
Sorting of FetchResults in TableView broken in xcode 26
Previously, I sorted my FetchResult in a TableView like this: @FetchRequest( sortDescriptors: [SortDescriptor(\.rechnungsDatum, order: .forward)], predicate: NSPredicate(format: "betragEingang == nil OR betragEingang == 0") ) private var verguetungsantraege: FetchedResults&lt;VerguetungsAntraege&gt; ... body ... Table(of:VerguetungsAntraege.self, sortOrder: $verguetungsantraege.sortDescriptors) { TableColumn("date", value:\.rechnungsDatum) { item in Text(Formatters.dateFormatter.string(from: item.rechnungsDatum ?? Date()) ) } .width(120) TableColumn("rechNrKurz", value:\.rechnungsNummer) { item in Text(item.rechnungsNummer ?? "") } .width(120) TableColumn("betrag", value:\.totalSum ) { Text(Formatters.currencyFormatter.string(from: $0.totalSum as NSNumber) ?? "kein Wert") } .width(120) TableColumn("klient") { Text(db.getKlientNameByUUID(id: $0.klient ?? UUID(), moc: moc)) } } rows: { ForEach(Array(verguetungsantraege)) { antrag in TableRow(antrag) } } There seem to be changes here in Xcode 26. In any case, I always get the error message in each line with TableColumn("title", value: \.sortingField) Ambiguous use of 'init(_:value:content:)' Does anyone have any idea what's changed? Unfortunately, the documentation doesn't provide any information.
0
0
121
3w
How do I stop iPadOS from thinking a drag is for a new window?
On iPadOS 26, dragging my draggable() View near the edge of the screen is causing a new window to open. This doesn't happen with .onDrag on iPadOS 26, or with either .draggable() or .onDrag on iPadOS 18.5. This is not something I'm intending to offer in my app, and doesn't really make sense. Is there any way to prevent this from happening? Is this a bug? I couldn't find any new documentation. The thing being dragged: the "Font" rectangle on the right side of the screen, which represents an item in my app that is reorder-able when multiple are present.
1
0
55
3w
timeline method is not being called for AppIntentTimelineProvider implementation on iOS 17 only
I have a widget that runs well on iOS 18. It is configurable and implements AppIntentTimelineProvider on the Provider. On iOS 17 it will call the placeholder method 7 times and not call the timeline method. The configuration intent implements WidgetConfigurationIntent. I've looked through the console logs and saw "ApplicationExtension record not found" but I'm not sure where to go from there. Why would the same widget work fine on iOS 18 and not 17? If I implement TimelineProvider and use a StaticConfiguration it works on iOS 17. Any help / guidance would be appreciated.
0
0
79
3w