in SwiftUI foundations: Build great apps with SwiftUI
Toolbar have navigationTitle with align leading.
I try to create same layout. but it fail
How was it possible?
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Created
.navigationDestination(isPresented) hangs after reboot (when called within 2 minutes of reboot) in watchOS when destination view contains @Environment(.dismiss).
Feedback: FB21077151
Second button hangs after reboot. Hangs in watchOS 26.0 and 26.4 on a physical device.
struct ContentView: View {
@State var presentView1 : Bool = false
@State var presentView2 : Bool = false
var body: some View {
NavigationStack {
VStack {
Button("Show View 1") {
presentView1.toggle()
}
Button("Show View 2") {
presentView2.toggle()
}
}
.navigationDestination(isPresented: $presentView1, destination: {TestView1()})
.navigationDestination(isPresented: $presentView2, destination: {TestView2()})
}
}
}
struct TestView1: View {
var body: some View {
Text("View 1")
}
}
struct TestView2: View {
@Environment(\.dismiss) var dismiss
var body: some View {
Text("View 2")
}
}
Problem
After launching the host app by tapping the widget (widgetURL), calls to:
WidgetCenter.shared.reloadAllTimelines() WidgetCenter.shared.reloadTimelines(ofKind: ...)
are ignored/deferred for an initial period right after the app opens. During this window, the widget does not reload its timeline and remains unupdated, no matter how many times I call the reload methods. After some time passes (typically ~30 seconds, sometimes shorter/longer), reload calls start working again.
There is also no developer-visible signal (no callback/error/acknowledgement) that the reload was ignored, so the app can’t detect the failure and can’t reliably recover the flow.
Question: Is this expected behavior (throttling/cooldown) after opening the app from a widget ? If so, is there any recommended workaround to update the widget reliably and quickly (or at least detect that the reload was not accepted)?
Any guidance would help.
Any logical reason why applying .sharedBackgroundVisibility(.hidden) to a ToolbarItem would not remove the spacing allocated for glass border?
Thus causing any element utilizing this functionality to appear offset from the regular buttons.
Or is this yet another magical Apple experience I am not blessed enough to understand.
A watchOS widget requires you set a container background:
.containerBackground(for: .widget) {
Color.black
}
But I see some .accessoryRectangular widgets, on the Smart Stack, using a glass background. From what I know there is no way to set this using .containerBackground. Does anyone know how to do this?
Thank you
I have an app that records video (and also provides a custom remote interface) so it needs to remain awake and in the foreground.
It sets;
UIApplication.shared.isIdleTimerDisabled = true
I've also tried catching willEnterForegroundNotification to ensure it resets it if the app is backgrounded and resumes;
.onReceive(
NotificationCenter.default.publisher(
for: UIApplication.willEnterForegroundNotification)
) { _ in
UIApplication.shared.isIdleTimerDisabled = true
}
However, it seems that on some devices it will still go to sleep. This seems to be the case when Adaptive Power Mode is on (or rather, I've not managed to reproduce it when Adaptive Power Mode is off) even when battery percentage is well over 20% (I sort of expected Low Power Mode to trigger this)
Am I missing something obvious? there must be a way to make sure media capture apps stay awake (I'm surprised AVFoundation doesn't do it anyway!)
If it is related to Adaptive Power Mode, is there any way to detect that programatically to at least provide a warning to the user that having it on will affect operation of the app?
UIHostingConfiguration on tvOS: focus permanently broken with multiple focusable SwiftUI views
Hi everyone,
I'm working on a tvOS app with a UICollectionView. Some cells embed SwiftUI content via UIHostingConfiguration, specifically a row of 3 buttons that should be individually focusable. The cell itself returns canBecomeFocused = false so focus passes through to the SwiftUI buttons.
The problem: after navigating focus into that section once, it becomes permanently unfocusable. Focus enters briefly, then immediately exits to nil on its own, without any user input. From that point on, the focus engine completely skips the section.
The exact same SwiftUI view works perfectly when embedded via UIHostingController instead.
How to reproduce
Press DOWN to move focus into the UIHostingConfiguration section
Focus lands on a SwiftUI button for a split second
Focus exits on its own and bumps to another section
The section is now dead, focus skips it on every subsequent navigation
What the system logs say (-UIFocusLoggingEnabled YES)
Right when focus enters, the system reports the SwiftUI focus items as "disappearing":
Ignoring focus update request for disappearing focus environment <UIKitFocusSectionResponderItem>
Then when searching for a new focusable item:
<SwiftUI._UIInheritedView> → (warning) No focusable items found.
<UIHostingContentView> → (warning) No focusable items found.
=== unable to find focused item in context. retrying with updated request. ===
The views are still in the hierarchy (verified by pointer), but the UIHostingContentView no longer exposes its virtual focus items. I also see mismatched parentFocusEnvironment on those items, pointing to a _UIHostingView from a completely different cell.
What I've tried
I've spent a lot of time on this with my colleagues, dug through the very limited documentation available online, and even used AI agents to help brainstorm. We tested 10 different approaches, none worked:
Overriding preferredFocusEnvironments to point to the UIHostingContentView
setNeedsFocusUpdate() / updateFocusIfNeeded(), rescan finds nothing
Forcing UIKit redraws (setNeedsLayout, setNeedsDisplay)
Removing .focusSection()
Removing all SwiftUI animations, identical behavior
Using canFocusItemAt: delegate instead of cell subclass, identical
remembersLastFocusedIndexPath = true, causes a separate focus trap
configurationUpdateHandler + setNeedsUpdateConfiguration(), config is rebuilt but virtual items stay deregistered
Verified the UIHostingContentView never leaves the hierarchy. It doesn't, its internal state is just corrupted
My workaround
I switched to UIHostingController with proper view controller containment. It works because the hosting controller is a full UIFocusEnvironment, so the focus engine can traverse it and it correctly maintains its virtual items.
Has anyone encountered this? Is there a known pattern for using UIHostingConfiguration on tvOS with multiple focusable SwiftUI elements? Or should I just file a Feedback?
Thanks for any help!
UIHostingConfiguration on tvOS: focus permanently broken with multiple focusable SwiftUI views
Hi everyone,
I'm working on a tvOS app with a UICollectionView. Some cells embed SwiftUI content via UIHostingConfiguration, specifically a row of 3 buttons that should be individually focusable. The cell itself returns canBecomeFocused = false so focus passes through to the SwiftUI buttons.
The problem: after navigating focus into that section once, it becomes permanently unfocusable. Focus enters briefly, then immediately exits to nil on its own, without any user input. From that point on, the focus engine completely skips the section.
The exact same SwiftUI view works perfectly when embedded via UIHostingController instead.
How to reproduce
Press DOWN to move focus into the UIHostingConfiguration section
Focus lands on a SwiftUI button for a split second
Focus exits on its own and bumps to another section
The section is now dead, focus skips it on every subsequent navigation
What the system logs say (-UIFocusLoggingEnabled YES)
Right when focus enters, the system reports the SwiftUI focus items as "disappearing":
Ignoring focus update request for disappearing focus environment <UIKitFocusSectionResponderItem>
Then when searching for a new focusable item:
<SwiftUI._UIInheritedView> → (warning) No focusable items found.
<UIHostingContentView> → (warning) No focusable items found.
=== unable to find focused item in context. retrying with updated request. ===
The views are still in the hierarchy (verified by pointer), but the UIHostingContentView no longer exposes its virtual focus items. I also see mismatched parentFocusEnvironment on those items, pointing to a _UIHostingView from a completely different cell.
What I've tried
I've spent a lot of time on this with my colleagues, dug through the very limited documentation available online, and even used AI agents to help brainstorm. We tested 10 different approaches, none worked:
Overriding preferredFocusEnvironments to point to the UIHostingContentView
setNeedsFocusUpdate() / updateFocusIfNeeded(), rescan finds nothing
Forcing UIKit redraws (setNeedsLayout, setNeedsDisplay)
Removing .focusSection()
Removing all SwiftUI animations, identical behavior
Using canFocusItemAt: delegate instead of cell subclass, identical
remembersLastFocusedIndexPath = true, causes a separate focus trap
configurationUpdateHandler + setNeedsUpdateConfiguration(), config is rebuilt but virtual items stay deregistered
Verified the UIHostingContentView never leaves the hierarchy. It doesn't, its internal state is just corrupted
My workaround
I switched to UIHostingController with proper view controller containment. It works because the hosting controller is a full UIFocusEnvironment, so the focus engine can traverse it and it correctly maintains its virtual items.
Has anyone encountered this? Is there a known pattern for using UIHostingConfiguration on tvOS with multiple focusable SwiftUI elements? Or should I just file a Feedback?
Thanks for any help!
You can find the code here : https://github.com/ThomasDutartre/focus-problem-tvos
I recored the problem here :
https://youtu.be/yPfM5AvU2ko
I have a very simple custom collection view layout that supports self-sizing. When a cell is selected, I expand the cell by modifying its constraints. This change (and the resulting effect on the collection view layout) is animated using [self.collectionView.collectionViewLayout invalidateLayout] followed by [self.collectionView layoutIfNeeded] within an animation closure.
When you first tap on a cell, it expands smoothly as expected. When you tap on it again to contract it, however, its content jumps before it shrinks again. How can I fix this?
For what it’s worth, I’ve noticed that neither UICollectionViewFlowLayout nor UICollectionViewCompositionalLayout have this issue, which suggests I’m doing self-sizing incorrectly.
Here’s a screen recording demonstrating the issue. I’ve also put together a minimal sample project.
I’m using Xcode 26.2 and iOS 26.2.1.
In my app i need to restrict the user to take screenshot or screen recording .
i used the following code snippet,
let field = UITextField()
let view = UIView(frame: CGRect(x: 0, y: 0, width: field.frame.self.width, height: field.frame.self.height))
// Following view can be customised if required
let newView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
newView.backgroundColor = .black
field.isSecureTextEntry = true
window.addSubview(field)
view.addSubview(newView)
window.layer.superlayer?.addSublayer(field.layer)
//field.layer.sublayers?.last!.addSublayer(window.layer)
if let lastSublayer = field.layer.sublayers?.last {
lastSublayer.addSublayer(window.layer)
}
field.leftView = view
field.leftViewMode = .always
My query is will below lines meet the Apple compliance?
will ther be any rejection while publishing to Appstore?
window.layer.superlayer?.addSublayer(field.layer)
field.layer.sublayers?.last!.addSublayer(window.layer).
In iOS 18, TabView with .tabViewStyle(.sidebarAdaptable) introduced a powerful adaptive pattern — tabs in compact, sidebar in regular. However, the current Tab API only supports a title and an image (icon). There is no way to provide a trailing accessory view (e.g., a secondary icon or indicator) for sidebar rows.
This is a meaningful gap in the API, because trailing accessories are a well-established pattern throughout UIKit and SwiftUI.
Precedent in Apple's own design language
Apple already supports trailing accessories in many analogous contexts:
UITableViewCell / UICollectionViewListCell — support accessories (disclosure indicators, checkmarks, custom views) via UICellAccessory.
UIListContentConfiguration — allows leading and trailing content in list rows.
SwiftUI List rows — support Label, HStack with trailing elements, .badge(), and swipeActions.
NavigationLink — automatically renders a disclosure chevron as a trailing accessory.
UITabSidebarItem (UIKit, iOS 18) — supports configurationUpdateHandler and cell accessories at the UIKit level.
The sidebar of a .sidebarAdaptable TabView is visually identical to a List — yet its rows lack the accessory support that List rows have had for years.
Real-world example: Photos app
Apple's own Photos app (iPadOS 18+) demonstrates this exact need. In its sidebar, the "Recently Deleted" row displays a trailing lock icon to indicate that authentication is required to view the album. This is a meaningful UX element — it communicates state at a glance, without requiring the user to tap into the item.
Third-party developers building with TabView(.sidebarAdaptable) have no public API to replicate this pattern. The Tab view builder's label closure is decomposed into a discrete title and image; any additional views (including Spacer() and trailing Image views within an HStack) are silently discarded by the system.
What we've tried
Custom label closure with HStack — trailing views are ignored. The system extracts only the first Image and Text.
.badge() modifier — only supports Int or Text, not custom views such as icons.
Label with complex content — the system normalizes it to icon + title.
The only viable path today is to bridge to UIKit's UITabBarController and customize UITabSidebarItem directly, which defeats the purpose of using SwiftUI's declarative TabView API.
Proposed API
A trailing accessory modifier on Tab, consistent with existing SwiftUI patterns:
Tab("Recently Deleted", systemImage: "trash", value: "deleted") {
RecentlyDeletedView()
}
.tabSidebarAccessory {
Image(systemName: "lock.fill")
.foregroundStyle(.secondary)
}
// Option B: Text accessory (e.g., counts, status labels)
Tab("Inbox", systemImage: "tray", value: "inbox") {
InboxView()
}
.tabSidebarAccessory {
Text("12")
.font(.subheadline)
.foregroundStyle(.secondary)
}
// Option C: Combined text + image accessory
Tab("Shared Albums", systemImage: "rectangle.stack", value: "shared") {
SharedAlbumsView()
}
.tabSidebarAccessory {
HStack(spacing: 4) {
Text("3 new")
.font(.caption)
.foregroundStyle(.secondary)
Image(systemName: "person.2.fill")
.foregroundStyle(.blue)
}
}
Environment
Platform: iPadOS / macOS Catalyst
iOS version: 18.0+
Xcode: 16.0+
Component: SwiftUI TabView with .tabViewStyle(.sidebarAdaptable)
Summary
The Tab API should support trailing accessory content for sidebar rows, bringing it in line with the accessory support already available in UITableViewCell, UICollectionViewListCell, UIListContentConfiguration, and SwiftUI List. Apple's own Photos app demonstrates the need for this capability, yet no public API exists for third-party developers to achieve it.
I have a view that conforms to DropDelegate. When a file is dragged from the Finder and dropped on the view, the performDrop(info:) method successfully extracts a URL from the item provider and returns true, but the drag image slides away as if the drop had been rejected. Why?
func performDrop(info: DropInfo) -> Bool {
bgColor = .yellow
let providers = info.itemProviders(for: [.fileURL])
print("performDrop, providers: \(providers.count)")
if let aProvider = providers.first
{
if aProvider.hasItemConformingToTypeIdentifier(UTType.url.identifier)
{
aProvider.loadItem(forTypeIdentifier: UTType.url.identifier)
{ (item, error) in
if let error = error {
print("Error retrieving item provider data: \(error.localizedDescription)")
return
}
if let url = item as? URL
{
print("Received file URL (from Data.1): \(url)")
}
else if let data = item as? Data, let url = URL(dataRepresentation: data, relativeTo: nil)
{
print("Received file URL (from Data.2): \(url)")
}
}
}
}
return true
}
Since we started building our application on Tahoe, all NSPopupButtons in the UI stop truncating when the window they're in is moved to a different screen.
Even though their frame is correct, if the selected item string is longer than what can fit, they just draw outside of their bounds, overlapping other neighbouring controls.
This is reproducible only in our app target even though they are not subclassed or overridden in any way. The same window copied to a test app doesn't have the issue.
Initially good
After dragging to another screen
Frame is correct in the View Hierarchy debugger, but the contents are incorrect.
Very simple constraint setup, with content compression resistance set lower to allow resizing below the intrinsic content size.
This is what happens on this simple test window. The rest of the popups in more complex windows are all bad right away, without requiring you to move them to a different screen.
When built on Sequoia, all is well regardless of which OS the app is run on.
Looking for ideas on how to troubleshoot this and figure out what's triggering it.
Topic:
UI Frameworks
SubTopic:
AppKit
I have a mac app using AppKit. I have a view that extends under the toolbar. It is very slightly blurred but still disturbs the readability of the toolbar items. In another window, I have a view that sits inside a NSScrollView and there the content is much more blurred and a bit dimmed under the toolbar.
Is there a way to make the not scrolled view behave like the one in the NSScrollView?
Topic:
UI Frameworks
SubTopic:
AppKit
Problem
After launching the host app by tapping the widget (widgetURL), calls to:
WidgetCenter.shared.reloadAllTimelines()
WidgetCenter.shared.reloadTimelines(ofKind: ...)
are ignored/deferred for an initial period right after the app opens. During this window, the widget does not reload its timeline and remains unupdated, no matter how many times I call the reload methods. After some time passes (typically ~30 seconds, sometimes shorter/longer), reload calls start working again.
There is also no developer-visible signal (no callback/error/acknowledgement) that the reload was ignored, so the app can’t detect the failure and can’t reliably recover the flow.
Question:
Is this expected behavior (throttling/cooldown) after opening the app from a widget ?
If so, is there any recommended workaround to update the widget reliably and quickly (or at least detect that the reload was not accepted)?
Any guidance would help.
We are currently testing our application under macOS 26 in Liquid Glass mode and noticed an issue with NSSegmentedCell.
Our app makes extensive use of NSCell-based drawing. Since macOS 26, when running in Liquid Glass mode, NSSegmentedCell does not render at the expected location.
The control itself appears visually correct, but it is clearly drawn offset from the rect it is supposed to occupy.
In compatibility mode, everything renders exactly as expected (same code, same layout).
To illustrate the issue, here are two screenshots of the same view:
Liquid Glass mode
👉 (screenshot 1 – segmented control visibly shifted)
Compatibility mode
👉 (screenshot 2 – correct rendering)
The regression is obvious when switching between the two modes.
This behavior has been present since the first macOS 26 release and is still reproducible with Xcode 26.2 (17C52).
I have already filed a report via Feedback Assistant (FB reference available if useful), but I’m posting here to see whether others are experiencing the same issue or have found a workaround.
Thanks.
Topic:
UI Frameworks
SubTopic:
AppKit
I need to detect whether a view controller is presented in a popover or in fullscreen mode, as on iPhone.
I checked viewController.popoverPresentationController but it returns a non-nil value even on iPhone, when it's clearly not in a popover.
I then checked viewController.presentationController?.adaptivePresentationStyle but it returns .formSheet even when it's presented in a popover!?! Why?
This whole adaptive presentation thingie is a mess. Heck, viewController.presentationController returns _UIPageSheetPresentationController even when the view controller is in a UINavigationController, so not presented at all.
Anybody got any ideas?
[Submitted as FB21961572]
When navigating from a tile in a scrolling LazyVGrid to a child view using .navigationTransition(.zoom) and then returning, the source tile can lag behind the rest of the grid if scrolling starts immediately after returning.
The lag becomes more pronounced as tile content gets more complex; in this simplified sample, it can seem subtle, but in production-style tiles (as used in both of my apps), it is clearly visible and noticeable.
This may be related to another issue I recently filed:
Source item disappears after swipe-back with .navigationTransition(.zoom)
CONFIGURATION
Platform: iOS Simulator and physical device
Navigation APIs: matchedTransitionSource + navigationTransition(.zoom)
Container: ScrollView + LazyVGrid
Sample project: ZoomTransition (DisappearingTile).zip
REPRO STEPS
Create a new iOS project and replace ContentView with the code below.
Run the app in sim or physical device
Tap any tile in the scrolling grid to navigate to the child view.
Return to the grid (back button or edge swipe).
Immediately scroll the grid.
Watch the tile that was just opened.
EXPECTED
All tiles should move together as one coherent scrolling grid, with no per-item lag or desynchronization.
ACTUAL
The tile that was just opened appears to trail behind neighboring tiles for a short time during immediate scrolling after returning.
MINIMAL CODE SAMPLE
import SwiftUI
struct ContentView: View {
@Namespace private var namespace
private let tileCount = 40
private let columns = [GridItem(.adaptive(minimum: 110), spacing: 12)]
var body: some View {
NavigationStack {
ScrollView {
LazyVGrid(columns: columns, spacing: 12) {
ForEach(0..<tileCount, id: \.self) { index in
NavigationLink(value: index) {
RoundedRectangle(cornerRadius: 16)
.fill(color(for: index))
.frame(height: 110)
.overlay(alignment: .bottomLeading) {
Text("\(index + 1)")
.font(.headline)
.foregroundStyle(.white)
.padding(10)
}
.matchedTransitionSource(id: index, in: namespace)
}
.buttonStyle(.plain)
}
}
.padding(16)
}
.navigationTitle("Zoom Transition Grid")
.navigationSubtitle("Open tile, go back, then scroll immediately")
.navigationDestination(for: Int.self) { index in
Rectangle()
.fill(color(for: index))
.ignoresSafeArea()
.navigationTransition(.zoom(sourceID: index, in: namespace))
}
}
}
private func color(for index: Int) -> Color {
let hue = Double(index % 20) / 20.0
return Color(hue: hue, saturation: 0.8, brightness: 0.9)
}
}
SCREEN RECORDING
Topic:
UI Frameworks
SubTopic:
SwiftUI
There is no way to make an instance of UISegmentedControl transparent like it's done in Photos or Camera. Especially it looks wrong when segmented control is put to a Liquid Glass container.
Setting background colour to nil or clear does not help
If a transparent image is set as a background image for state and bar metrics, it kills liquid glass selection and segments started to look wrong
How can the standard gray-ish background can be removed?
Consider the following code on iOS:
struct ContentView: View {
@State private var timerInterval = Date(timeIntervalSince1970: 0) ... Date(timeIntervalSince1970: 0)
var body: some View {
VStack {
ProgressView(
timerInterval: timerInterval,
countsDown: true
)
Button {
let now = Date()
let then = now.addingTimeInterval(5)
timerInterval = now ... then
} label: {
Text("Start")
}
}
.padding()
}
}
When I tap on the Start button, the progress view starts animating as expected, and its label is displaying the remaining time.
However, at the very end, when the countdown reaches zero, the blue bar of the progress view doesn't reach zero and still has some progress left forever.
Is this the expected behavior or a bug? Is there a way to make the bar reach zero without implementing my own custom view?
Thanks in advance!
Topic:
UI Frameworks
SubTopic:
SwiftUI