import SwiftUI
import OsLog
let logger = Logger(subsystem: "Test", category: "Test")
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
.task {
logger.info("Hallo")
}
}
}
#Preview {
ContentView()
}
27 | .padding()
28 | .task {
29 | logger.info(__designTimeString("#6734_2", fallback: "Hallo"))
| `- error: argument must be a string interpolation
30 | }
31 | }
Should OsLog be compatible with __designTimeString?
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I was doing an app which had several "camera" buttons each one dedicated to taking/storing/reviewing/deleting an image associated with a variable URL but what should have been a simple no brainer turned out to be a programming nightmare.
To cut a long story short there is a bug in the sheet handling wherebye even tho you have separate instance for each button the camera/picker cylcles sequentially thru the stack of instances for any action finally always placing the image in the first URL. Working with myself debugging, all major AIs (Grok, Claude, Gemini and Perplexity) after 4 x 12hr+ days we finally managed to crack a solution. What follows is Groks interpretation (note it misses the earlier problem of instance cycling!!) ...
You can follow the discussion here: https://x.com/i/grok/share/KHeaUPladURmbFq5qy9W506er
but be warned its long a detailed but if you are having problems then read ...
**Bug Report: Race Conditions with UIImagePickerController in SwiftUI Sheet
**
Environment:
SwiftUI, iOS 17.7.5
Device: iPad Pro (12.9-inch, 2nd generation)
Xcode Version: [Insert your Xcode version]
Date: March 30, 2025
**Issue 1: Multiple Instances of UIImagePickerController Spawned After Dismissal
**
Description:
When using a UIImagePickerController wrapped in a UIViewControllerRepresentable and presented via a SwiftUI .sheet, selecting "Use Photo" resulted in multiple unintended instances of the picker being initialized and presented. The console logs showed repeated "Camera initialized" and "Camera sheet appeared" messages (e.g., multiple <UIImagePickerController: 0x...> instances) after the initial dismissal, despite the sheet being dismissed programmatically.
Reproduction Steps:
Create a SwiftUI view with a button that sets a @State variable showCamera to true.
Present a UIImagePickerController via .sheet(isPresented: $showCamera).
Update a @Binding variable (e.g., photoLocation: URL?) in imagePickerController(_:didFinishPickingMediaWithInfo:) after saving the image.
Dismiss the picker with picker.dismiss(animated: true) and presentationMode.wrappedValue.dismiss().
Observe that updating the @Binding variable triggers a view re-render, causing the .sheet to re-present multiple times before finally staying dismissed.
Root Cause:
A race condition occurred between the view update (triggered by changing photoLocation) and the dismissal of the picker. During the re-render, showCamera remained true momentarily, causing the .sheet modifier to re-evaluate and spawn new picker instances before the onDismiss closure could reset showCamera to false.
The fix involved delaying the @Binding update (photoLocation) until after the picker and sheet were fully dismissed, ensuring showCamera was reset to false before the view re-rendered:
Introduced an onPhotoPicked: (URL) -> Void closure to decouple the photoLocation update from the dismissal timing.
Modified the coordinator to call onPhotoPicked and reset showCamera before initiating dismissal:swift
Issue 2: Single Unintended Picker Reopen After Initial Fix
Description:
After addressing the multiple-instance issue, a single unintended reopen of the picker persisted. The logs showed one additional "Camera initialized" and "Camera sheet appeared" after "Use Photo," before the final dismissal.
Reproduction Steps:
Reproduction Steps:
Use the initial fix with onPhotoPicked and delayed photoLocation update.
Take a photo and select "Use Photo."
Observe one extra picker instance appearing briefly before dismissal completes.
Root Cause:
The @Binding update (photoLocation) was still occurring too early in the dismissal sequence. Although delayed until after picker.dismiss, the view re-render happened while showCamera was still true during the dismissal animation, causing the .sheet to re-present once before onDismiss reset showCamera.
Resolution:
The fix ensured showCamera was set to false before the picker dismissal animation began, preventing the .sheet from re-evaluating during the transition:
Moved the dismissCamera() call (which sets showCamera to false) into the onPhotoPicked callback, executed before picker.dismiss:
CameraView(
photoLocation: $photoLocation,
storeDirectory: storeDirectory,
onPhotoPicked: { url in
print("Photo picked callback for \(id), setting photoLocation: \(url)")
self.photoLocation = url
self.cameraState.dismissCamera() // Sets showCamera to false first
}
)
Kept the dismissal sequence in the coordinator:
DispatchQueue.main.async {
self.parent.onPhotoPicked(fileURL)
picker.dismiss(animated: true) {
self.parent.presentationMode.wrappedValue.dismiss()
}
}
This synchronized the state change with the dismissal, ensuring showCamera was false before the view re-rendered, eliminating the single reopen.
Request:
Could the SwiftUI team clarify if this behavior is expected, or consider improving the .sheet modifier to better handle state transitions during UIKit controller dismissal? A more robust bridge between SwiftUI’s declarative state and UIKit’s imperative lifecycle could prevent such race conditions.
Background
I have a SwiftUI app that uses OSLog and the new Logger framework. In my SwiftUI views, I would like to use something like Self._logChanges() to help debug issues.
After some trial and error, I can see the messages appear in the System console log for the app I am debugging using the com.apple.SwiftUI subsystem.
Problem
I'd like to see those same messages directly in Xcode's console window so I can filter them as needed. How do I do that?
Thanks! -Patrick
As in the title: openImmersiveSpace works as expected. The ImmersiveSpace in the ID opens normally but the function never resolves a Result. Here is a workaround I used to make user it was on the UI thread and scenePhase was active:
`
@MainActor func openSpaceWithStateCheck() async {
if scenePhase == .active {
Task {
switch await openImmersiveSpace(id: "RoomCaptureInteraction") {
case .opened:
isCapturingImagery = true
break
case .error:
print("!! An error occurred when trying to open the immersive space captureRoomImagery")
case .userCancelled:
print("!! The user declined opening immersive space captureRoomImagery")
@unknown default:
print("!! unknown default result of opening space")
break
}
}
} else {
print("Scene not active, deferring immersive space opening")
}
}
I'm on visionOS 2.4 and SDK 2.2.
I have tried uninstalling the app and rebuilding. Tried simply opening an empty ImmersiveSpace.
The consistency of the ImmersiveSpace opening at least means I can work around it. Even dismissImmersiveSpace works normally and closes the immersive space. But a workaround seems hamfisted.
Problem
Setting ".environment(.layoutDirection, .rightToLeft)" to a view programmatically won't make buttons in menu to show right to left.
However, setting ".environment(.locale, .init(identifier: "he-IL"))" to a view programmatically makes buttons in menu to show Hebrew strings correctly.
Development environment: Xcode 16.x, macOS 15.3.1
Target iOS: iOS 17 - iOS 18
The expected result is that the button in the menu should be displayed as an icon then a text from left to right.
Code to demonstrate the problem:
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Buttons in menu don't respect the environment value of .layoutDirection")
.font(.subheadline)
.padding(.bottom, 48)
/// This button respects both "he-IL" of ".locale" and ".rightToLeft" of ".layoutDirection".
Button {
print("Button tapped")
} label: {
HStack {
Text("Send")
Image(systemName: "paperplane")
}
}
Menu {
/// This button respects "he-IL" of ".locale" but doesn't respect ".rightToLeft" of ".layoutDirection".
Button {
print("Button tapped")
} label: {
HStack {
Text("Send")
Image(systemName: "paperplane")
}
}
} label: {
Text("Menu")
}
}
.padding()
.environment(\.locale, .init(identifier: "he-IL"))
.environment(\.layoutDirection, .rightToLeft)
}
}
I was determined to fully rely on SwiftUI's navigation system giving the fact I'm starting a new project - strongly reconsidering this after a very basic requirement.
Namely: navigate between my two screens while wanting to hide the back button label.
One of them has a large navigation title
The other one has no navigation title
The problem is that back button icon simply jumps from top, a little bit down (where the title is supposed to be) and then back to top while navigating - resulting in a rough bouncy animation.
struct ParentView: View {
var body: some View {
NavigationStack {
WelcomeView()
.navigationDestination(for: WelcomeRoute.self) { route in
destinationView(for: route)
}
}
}
...
}
struct WelcomeView: View {
var body: some View {
ScrollView {
VStack {
...
NavigationLink(value: WelcomeRoute.Routes.next) {
Text("Next screen")
}
}
}
.navigationTitle("WELCOME")
.navigationBarTitleDisplayMode(.large)
}
}
struct NextWelcomeView: View {
var body: some View {
ScrollView {
VStack {
....
Text("Hello")
}
}
.toolbarRole(.editor)
}
}
Since tvOS 18, my Picker view with inline style is not showing the checkmark on the selected item.
enum Flavor: String, Identifiable {
case chocolate, vanilla, strawberry
var id: Self { self }
}
struct ContentView: View {
@State private var selectedFlavor: Flavor = .chocolate
var body: some View {
NavigationView {
Form {
Picker("Flavor", selection: $selectedFlavor) {
Text("Chocolate").tag(Flavor.chocolate)
Text("Vanilla").tag(Flavor.vanilla)
Text("Strawberry").tag(Flavor.strawberry)
}.pickerStyle(.inline)
}
}
}
}
Am I missing something? When I run this on tvOS 17.x, it works fine.
I'm trying to make a timetable app for my Apple Watch, and it has all actually been going pretty smoothly until this random error started showing up when I try to build my application. Here's a code snippet:
// all on top level:
class globalStorage {
static let shared = globalStorage() // line 27
@State @AppStorage(runningKey) var termRunningGB = false
@State @AppStorage(ghostWeekKey) var ghostWeekGB = false
@State @AppStorage(startDateKey) var startDateGB = Date.now
var currentCourse: Course = getCurrentClass(date: .now)
}
let storage = globalStorage.shared // &lt;&lt; ERRORING HERE (line
// ...
@main
struct myApp: App { /* ... */ }
Can anybody tell me what is happening? (And, of course, how to fix it?)
Furthermore, upon removing the offending line (let storage = globalStorage.shared) (and replacing all callers of said variable with 'globalStorage.shared' to bypass the variable) the error has decided to settle on line 27, where i define the 'shared' thing in the class.
[ I just went back to try more solutions, I have resolved it but forgot to give my solution here. Now I've forgotten how I fixed it. I do know that I moved currentCourse out of the class, that most likely was it I think.]
All of this code is on GitHub: https://github.com/the-trumpeter/Timetaber-for-iWatch
I would like to understand how to programmatically set the position of a cursor in a SwiftUI TextField.
In UIKit this can be done using the selectedTextRange property, but I couldn't find a similar way to achieve this with pure SwiftUI.
I want to figure out something like setCursorPosition (index:) - maybe by tracking the position in a @State or any other way.
I understand that I can do this using UIViewRepresentable but I am looking for a pure SwiftUI solution and wanted to know if there is any.
Basic Information
Please provide a descriptive title for your feedback:
Sheet presentationDetents breaks after rapid open/dismiss cycles
Which platform is most relevant for your report?
iOS
Description
Steps to Reproduce:
Create a sheet with presentationDetents([.medium])
Rapidly perform these actions multiple times (usually 3-4 times):
a. Open the sheet
b. Immediately scroll down to dismiss
Open the sheet again
Observe that the sheet now appears at .large size, ignoring the .medium detent
Expected Result:
Sheet should consistently maintain .medium size regardless of how quickly
it is opened and dismissed.
Actual Result:
After rapid open/dismiss cycles, the sheet ignores .medium detent and
appears at .large size.
Reproduction Rate:
Occurs consistently after 3-4 rapid open/dismiss cycles
More likely to occur with faster open/dismiss actions
Configuration:
iOS 18
Xcode 16.0 (16A242d)
SwiftUI
Device: iPhone 14
I've encountered an issue when using TabView inside a Popover on iPadOS, and I wanted to see if anyone else has run into this or if there's a known workaround before I file a bug report.
Issue:
When placing a TabView inside a Popover on iPadOS, the tab bar is not center-aligned correctly if the popover’s arrow appears on either the leading or trailing edge. It seems that the centering calculation for the TabView includes the width of the arrow itself.
If the popover arrow is on the left, the tabs inside the TabView are pushed to the left.
If the popover arrow is on the right, the tabs shift toward the right.
This suggests that SwiftUI is incorporating the popover arrow’s width into the alignment calculation, which results in the misalignment.
Questions:
Has anyone else encountered this behavior?
Is there a known workaround to ensure proper centering?
If this is indeed a bug, should I file a report through Feedback Assistant?
Any insights would be greatly appreciated!
Super easy to reproduce.
Swiping to delete on the last remaining item in the list causes an index out of bounds exception. If you have 2 items in your list, it will only happen when you delete the last remaining item.
From my testing, this issue occurs on 18.3.1 and onward (the RC it happens). I didn't test 18.3.0 so it might happen there as well.
The only workarounds I have found is to add a delay before calling my delete function:
OR
to comment out the Toggle.
So it seems as though iOS 18.3.x added a race condition in the way the ForEach accesses the values in its binding.
Another thing to note, this also happens with .swipeActions, EditMode, etc... any of the built in ways to delete an item from a list.
import SwiftUI
struct ContentView: View {
@StateObject var viewModel = ContentViewModel()
var body: some View {
List {
ForEach($viewModel.items) { $item in
HStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text($item.text.wrappedValue)
Spacer()
Toggle(String(""), isOn: $item.isActive)
.labelsHidden()
}
}
.onDelete(perform: delete)
}
}
func delete(at offsets: IndexSet) {
// uncomment task to make code not crash
// Task {
viewModel.deleteItem(at: offsets)
// }
}
}
struct MyItem: Identifiable {
var id: UUID = UUID()
var text: String
var isActive: Bool
}
class ContentViewModel: ObservableObject {
@Published var items: [MyItem] = [MyItem(text: "Hello, world!", isActive: false)]
func deleteItem(at offset: IndexSet) {
items.remove(atOffsets: offset)
}
}
In tvOS when using NavigationStack inside NavigationSplitView as below:
@State private var selectedItem: String?
@State private var navigationPath = NavigationPath() // Track navigation state manually
var body: some View {
NavigationSplitView {
List(selection: $selectedItem) {
Button("Item 1") { selectedItem = "Detail View 1" }
Button("Item 2") { selectedItem = "Detail View 2" }
}
} detail: {
NavigationStack(path: $navigationPath) {
DetailView()
.navigationDestination(for: String.self) { value in
Text("New Screen: \(value)")
}
}
}
}
}
This example completely breaks the animation inside NavigationStack while navigating between different views, using withAnimation also breaks the navigation as the old view seems to be still in stack and is shown in the new view background.
I have also submitted bug report: https://feedbackassistant.apple.com/feedback/16933927
I'm trying to render a markdown with a link using Text.
If the URL of the link is a static string, then no problem. If the URL is a property, then OpenURLAction gets a string ‘%25@’. I think this may be a bug.
struct ContentView: View {
let url = "https://www.google.com"
var body: some View {
Text("[Terms of Service](\(url))")
.environment(\.openURL, OpenURLAction(handler: { url in
print(url)
return .handled
}))
}
}
I'm developing the VisionOS app. I want to know how to play spatial audio in addition to RealityKit? If it's iOS or macOS, how to play spatial audio in addition to RealityKit?
Pasting either plain or styled text into any TextEditor results in a memory leak.
import SwiftUI
struct EditorView: View {
@State private var inputText: String = ""
var body: some View {
VStack{
TextEditor(text: $inputText)
.frame(minHeight: 150)
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Button ("Button 1") {
print ("Button 1");
}
.keyboardShortcut("k", modifiers: .command)
Button ("Button 2") {
print ("Button 2");
}
.keyboardShortcut("k", modifiers: .command)
}
}
}
I the above snippet, I have assigned the same keyboard shortcut (cmd +k) to 2 different buttons. According to the docs, if multiple controls are associated with the same shortcut, the first one found is used.
How do I figure out if Button 1 would be found first during the traversal or Button 2 ?
Is it based on the order of declaration? Is it always the case that Button 1 would be found first since it was declared before Button 2 ?
In Vision OS app, We have two types of windows:
Main App Window – This is the default window that launches when the app starts. It displays the video listings and other primary content.
Immersive Space Window – This opens only when a user starts streaming or playing a video.
Issue:
When entering the immersive space, the main app window remains visible in front of it unless manually closed. To avoid this, I currently close the main window when transitioning to immersive space and reopen it when exiting. However, this causes the app to restart instead of resuming from its previous state.
Desired Behavior:
I want the main app window to retain its state and seamlessly resume from where it was before entering immersive mode, rather than restarting.
Attempts & Challenges:
Tried managing opacity, visibility, and state preservation, but none worked as expected.
Couldn’t find a way to push the main window to the background while bringing the immersive space to the foreground.
Looking for a solution to keep the main window’s state intact while transitioning between immersive and normal modes.
With the introduction of the new matchedTransitionSource from iOS 18, we can apply a zoom transition in the navigation view using .navigationTransition(.zoom) This works well for zoom animations.
However, when I try to apply a matched geometry effect to views that are similar in the source and destination views, the zoom transition works, but those views don't transition seamlessly as they do with a matched geometry effect.
Is it possible to still use matched geometry for subviews of the source and destination views along with the new navigationTransition?
Here’s a little demo that reproduces this behaviour:
struct ContentView: View {
let colors: [[Color]] = [
[.red, .blue, .green],
[.yellow, .purple, .brown],
[.cyan, .gray]
]
@Namespace() var namespace
var body: some View {
NavigationStack {
Grid(horizontalSpacing: 50, verticalSpacing: 50) {
ForEach(colors, id: \.hashValue) { rowColors in
GridRow {
ForEach(rowColors, id: \.self) { color in
NavigationLink {
DetailView(color: color, namespace: namespace)
.navigationTransition(
.zoom(
sourceID: color,
in: namespace
)
)
.edgesIgnoringSafeArea(.all)
} label: {
ZStack {
RoundedRectangle(cornerRadius: 5)
.foregroundStyle(color)
.frame(width: 48, height: 48)
Image(systemName: "star.fill")
.foregroundStyle(Material.bar)
.matchedGeometryEffect(id: color,
in: namespace,
properties: .frame, isSource: false)
}
}
.matchedTransitionSource(id: color, in: namespace)
}
}
}
}
}
}
}
struct DetailView: View {
var color: Color
let namespace: Namespace.ID
var body: some View {
ZStack {
color
Image(systemName: "star.fill")
.resizable()
.foregroundStyle(Material.bar)
.matchedGeometryEffect(id: color,
in: namespace,
properties: .frame, isSource: false)
.frame(width: 100, height: 100)
}
.navigationBarHidden(false)
}
}
#Preview {
ContentView()
}
The save credentials prompt is not shown after clicking the submit button in the following setup. The prompt is shown if I move the email field before the login field.
Is it really required to have login and password fields at the end of the registration form? Or is there some API that can trigger the prompt?
struct FakeRegistrationView: View {
@State private var login = ""
@State private var password = ""
@State private var repeatPassword = ""
@State private var email = ""
var navigateBack: () -> Void
var body: some View {
VStack(spacing: 16) {
TextField("Login", text: $login)
.textFieldStyle(.roundedBorder)
.textContentType(.username)
.disableAutocorrection(true)
.autocapitalization(.none)
.frame(maxWidth: 300)
SecureField("Password", text: $password)
.textFieldStyle(.roundedBorder)
.textContentType(.newPassword)
.disableAutocorrection(true)
.autocapitalization(.none)
.frame(maxWidth: 300)
SecureField("Repeat password", text: $repeatPassword)
.textFieldStyle(.roundedBorder)
.textContentType(.newPassword)
.disableAutocorrection(true)
.autocapitalization(.none)
.frame(maxWidth: 300)
TextField("Email", text: $email)
.textFieldStyle(.roundedBorder)
.textContentType(.emailAddress)
.disableAutocorrection(true)
.autocapitalization(.none)
.frame(maxWidth: 300)
Button {
Task {
try? await Task.sleep(for: .seconds(2))
navigateBack()
}
} label: {
Text("Submit")
}
.buttonStyle(.borderedProminent)
}
}
}