There is an issue with SwiftUI where it is incorrectly instantiating the navigation destination view with a new identity for a navigation stack that is being removed.
Here is a minimal reproducible example:
struct ContentView: View {
@State private var signedIn = false
var body: some View {
if signedIn {
navigationStack(isSignedIn: true)
} else {
navigationStack(isSignedIn: false)
}
}
private func navigationStack(isSignedIn: Bool) -> some View {
NavigationStack(path: .constant(NavigationPath([1]))) {
EmptyView()
.navigationDestination(for: Int.self) { _ in
VStack {
Text(isSignedIn ? "Signed In" : "Signed Out")
.foregroundStyle(Color.red)
Button(isSignedIn ? "Sign Out" : "Sign In") {
signedIn = !isSignedIn
}
}
.onFirstAppear {
print(isSignedIn ? "signed in" : "signed out")
}
}
}
}
}
struct OnFirstAppearView: ViewModifier {
@State private var hasAppeared = false
var onAppear: () -> Void
func body(content: Content) -> some View {
content
.onAppear {
if hasAppeared { return }
hasAppeared = true
onAppear()
}
}
}
extension View {
func onFirstAppear(_ onAppear: @escaping () -> Void) -> some View {
ModifiedContent(content: self, modifier: OnFirstAppearView(onAppear: onAppear))
}
}
When you launch the app it will print "signed out", but when you tap to Sign In it will print "signed out" and "signed in". This shows that onAppear is incorrectly being called for a view that is disappearing and worse yet, it is with a new identity.
The onFirstAppear modifier was created to help with detecting the identity change of the view.
Tested on Xcode 16.4, on simulator using iOS 18.5 and also on physical device using iOS 18.5.
Link to Feedback sent on Feedback Assistant: https://feedbackassistant.apple.com/feedback/18336684
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
Activity
Hi! I'm seeing some weird animation issues building the Food Truck sample application.^1 I'm running from macOS 15.4 and Xcode 16.3. I'm building the Food Truck application for macOS. I'm not focusing on iOS for now.
The FoodTruckModel adds new Order values with an animation:
// FoodTruckModel.swift
withAnimation(.spring(response: 0.4, dampingFraction: 1)) {
self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator))
}
This then animates the OrdersTable when new Order values are added.
Here is a small change to OrdersTable:
// OrdersTable.swift
- @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)]
+ @State private var sortOrder = [KeyPathComparator(\Order.creationDate, order: .reverse)]
Running the app now inserts new Order values at the top.
The problem is I seem to be seeing some weird animation issues here. It seems that as soon as the new Order comes in there is some kind of weird glitch where it appears as if part the animation is coming from the side instead of down from the top:
What's then more weird is that if I seem to affect the state of the Table in any way then the next Order comes in with perfect animation.
Scrolling the Table fixes the animation.
Changing the creationData sort order from reverse to forward and back to reverse fixes the animation.
Any ideas? Is there something about how the Food Truck product is built that would cause this to happen? Is this an underlying issue in the SwiftUI infra?
I am using ".navigationTransition(ZoomNavigationTransition.zoom(sourceID: xxx, in: xxx))" to zooms the appearing view from a source view .
When the appearing view dismissed, I can only click other view after a delay .
It seems that the transition is not finished immediately when the appearing view dismissed . After a delay, the transition finished, than I can click other view.
struct ContentView: View {
@State private var path: NavigationPath = NavigationPath()
@Namespace private var namespace
var body: some View {
NavigationStack(path: $path) {
VStack(spacing: 0) {
ForEach(["aaa", "bbb"], id: \.self) { string in
Text(string)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 2)
.contentShape(Rectangle())
.onTapGesture {
path.append(string)
}
.matchedTransitionSource(id: string, in: namespace)
}
}
.navigationDestination(for: String.self, destination: { route in
Text(route)
.navigationTransition(ZoomNavigationTransition.zoom(sourceID: route, in: namespace))
})
}
}
}
When using sheet on appearing view, It seems that the transition is finished immediately when the appearing view dismissed.
extension String: Identifiable {
public var id: String { return self }
}
struct ContentView: View {
@State private var path: NavigationPath = NavigationPath()
@Namespace private var namespace
@State private var stringToSheet: String?
var body: some View {
NavigationStack(path: $path) {
VStack(spacing: 0) {
ForEach(["aaa", "bbb"], id: \.self) { string in
Text(string)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 2)
.contentShape(Rectangle())
.onTapGesture {
stringToSheet = string
}
.matchedTransitionSource(id: string, in: namespace)
}
}
.sheet(item: $stringToSheet) { newValue in
Text(newValue)
.navigationTransition(ZoomNavigationTransition.zoom(sourceID: newValue, in: namespace))
}
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
My assumption has always been that [NSApp runModalForWindow:] runs a modal window in NSModalPanelRunLoopMode.
However, while -[NSApplication _doModalLoop:peek:] seems to use NSModalPanelRunLoopMode when pulling out the next event to process via nextEventMatchingMask:untilDate:inMode:dequeue:, the current runloop doesn't seem to be running in that mode, so during -[NSApplication(NSEventRouting) sendEvent:] of the modal-specific event, NSRunLoop.currentRunLoop.currentMode returns kCFRunLoopDefaultMode.
From what I can tell, this means that any event processing code that e.g. uses [NSTimer addTimer:forMode:] based on the current mode will register a timer that will not fire until the modal session ends.
Is this a bug? Or if not, is the correct way to run a modal session something like this?
[NSRunLoop.currentRunLoop performInModes:@[NSModalPanelRunLoopMode] block:^{
[NSApp runModalForWindow:window];
}];
[NSRunLoop.currentRunLoop limitDateForMode:NSModalPanelRunLoopMode];
Alternatively, if the mode of the runloop should stay the same, I've seen suggestions to run modal sessions like this:
NSModalSession session = [NSApp beginModalSessionForWindow:theWindow];
for (;;) {
if ([NSApp runModalSession:session] != NSModalResponseContinue)
break;
[NSRunLoop.currentRunLoop limitDateForMode:NSModalPanelRunLoopMode];
}
[NSApp endModalSession:session];
Which would work around the fact that the timer/callbacks were scheduled in the "wrong" mode. But running NSModalPanelRunLoopMode during a modal session seems a bit scary. Won't that potentially break the modality?
I've got a UIKit app that displays a lot of text, and we've completely turned off the system text selection menu and we show our own custom thing instead, to increase discoverability of our text selection actions. But now that iOS 26 can show the full menu even on iPhone, we're looking at switching back to the system menu.
It still shows a smaller horizontal-layout menu at first, and then you tap the > symbol to expand to the full menu. Is it possible to jump straight to the full menu, and skip the smaller horizontal one entirely?
Hello all,
I'm confused about how to show lanes in CarPlay.
I understand CPLaneGuidance and CPLane
I don't find anywhere where to tell Carplay which icon to show for each lane.
I've found some information saying we put the icon in CPManeuver, but then CPManeuver is linked to only one CPLaneGuidance, and we can put only one icon in CPManeuver.
At the same time, we might have multiple lanes.
Any help, tips, or examples would be highly helpful.
I'm using SwiftUI's TextEditor. I'd like to include an undo button in my UI that operates on the TextEditor. I don't see a way to hook this up. You can get the UndoManager from the environment, but this is not the undo manager the TextEditor is using. I know that UITextView uses an undocumented UndoManager (_UITextUndoManager) and I've accessed that before when using a UIViewRepresentable wrapper around UITextView. I'd like to achieve the same with TextEditor.
Topic:
UI Frameworks
SubTopic:
SwiftUI
I'd like to support different template views within a ViewThatFits for items within a list, allowing the list to optimize its layout for different devices.
Within the child views is a Text view that is bound to the name of an item. I'd rather the Text view simply truncate the text as necessary although it instead is influencing which view is chosen by ViewThatFits. I'd also rather not artificially set the maxWidth of the Text view as it artificially limits the width on devices where it's not necessary (e.g. iPad Pro vs. iPad mini or iPhone).
Any guidance or suggestions on how this can be accomplished as it looks very odd for the layout of one row in the list to be quite different than the rest of the rows.
Is there any way to influence the corner radius of a selection in the list? Looking at the native Apple Mail app in the iOS 26, it should be.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hi,
I am trying to create a local backup + restore when using SwiftUI and CoreData but I am facing errors left and right. the latest error I am stuck on is:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'
Here is what am trying to do:
Creating a backup (already solved using NSPersistentStoreCoordinator.migratePersistentStore(_:to:options:type:))
Create a new NSPersistentContainer and call its NSPersistentContainer.loadPersistentStores(completionHandler:) (already solved, load is successful)
Update the .environment(.managedObjectContext, viewModel.context) so that SwiftUI uses the new context. (HERE is where the error appears)
Any help would be appreciated.
Here is some sample code of SwiftUI part of the main view:
class ViewModel: ObservableObject {
@Published var context: NSManagedObjectContext
}
@main
struct MyApp: App {
@StateObject var viewModel: ViewModel
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, viewModel.context)
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
I have added multiple status icons to my project, in the form of .icon files created with Icon Composer. The main app icon works, but the status icons are not working.
I am attempting to load the images from the asset catalog using NSImage imageNamed:, and apply them to the NSApp dockTile using NSGlassEffectContainerView. I don't even know if that attempt is going to work, as I never get past the stage of NSImage loading the icons.
Maybe someone on the forums knows what to do there? I'd be willing to use one of my coding support incidents to work through this if necessary, as my two incidents will expire as my subscription rolls over in August anyway.
My project lives at https://github.com/losnoco/cog/, and the Tahoe attempt WIP lives in the wip.tahoe branch, with the latest commit as of this post being the attempt to adapt the Dock Icon generation.
I'd love to know if I can adapt this easily. I'm also still trying to support existing non-Glass custom .png icons the user can add to their profile folder with buttons in the preferences, as well as supporting legacy status icons on pre-Tahoe installs. I also try to add a progress bar to the dock tile view when the app is processing something at length.
I am trying to work with the data inside the barcode string in shared PKPass.
The documentation shows that is should look for @property (nonatomic, readonly, nullable) PKBarcode *primaryBarcode;
I have tried to use it like this
guard let code = pass.primaryBarcode?.message else { return }
I get a constant message that PKPass has no member primaryBarcode
The PKPass.h file in my IOS SDK does not seem to include the @property primaryBarcode or @property barcode.
I am running Xcode 16.4 (16F6) and my app target is 17.6 + Is there a restriction on this property?
I cannot find an SDK later than mine - the App Store does not offer one.
I am unsure of this is a public or private issue - does anyone know?
Thanks for reading this.
Max
Topic:
UI Frameworks
SubTopic:
SwiftUI
Is there a way to detect when your apps (or any app I guess) is being moved by the user clicking and dragging the main window around the desktop at all?
I'm trying to find out if there's a way I can find out if a window is being clicked and dragged and whether there's certain triggers to the movement a little bit like shaking an iPhone with Shake to Undo.
Thanks
Hi, I've got an app that displays markdown in UITextView / NSTextView.
I would like it to behave like Notes app does, that is if user types the line start modifier, e.g:
"# "
or
"> "
I would like the keyboard to show a capitalized letters.
I've tried looking into overriding insertText - and it breaks the predictive text (can not insert white space).
I've tried implementing UITextInputTokenizer but no luck either.
Like I said, I see the Notes app does it perfectly, so maybe I'm missing something obvious or there is a way to do it without interrupting the auto-correction and predictive text.
Ideally same thing can be applied to the NSTextView as the app support both platforms.
I want to record screen ,and than when I call the method stopCaptureWithHandler:(nullable void (^)(NSError *_Nullable error))handler to stop recording and saving file. before call it,I check the value record of RPScreenRecorder sharedRecorder ,the value is false , It's weird! The screen is currently being recorded !
I wonder if the value of [RPScreenRecorder sharedRecorder].record will affect the method stopCaptureWithHandler:
-(void)startCaptureScreen {
[[RPScreenRecorder sharedRecorder] startCaptureWithHandler:^(CMSampleBufferRef _Nonnull sampleBuffer, RPSampleBufferType bufferType, NSError * _Nullable error) {
//code
} completionHandler:^(NSError * _Nullable error) {
//code
}];
}
- (void)stopRecordingHandler {
if([[RPScreenRecorder sharedRecorder] isRecording]){
// deal error .sometime isRecording is false
}else {
[[RPScreenRecorder sharedRecorder] stopCaptureWithHandler:^(NSError * _Nullable error) {
}];
}
}
here are my code.
Description
When using UIDocumentPickerViewController with allowsMultipleSelection = false, I expect that selecting a file will dismiss only the document picker.
However, if a user quickly taps the same file multiple times, the picker dismisses both itself and the presenting view controller (i.e., it pops two levels from the view controller stack), which leads to unintended behavior and breaks presentation flow.
Expected Behavior
Only UIDocumentPickerViewController should be dismissed when a file is selected—even if the user taps quickly or multiple times on the same file.
Actual Behavior
When tapping the same file multiple times quickly, the picker dismisses not only itself but also the parent view controller it was presented from.
Steps to Reproduce
Create a simple view controller and present another one modally over it.
From that presented view controller, present a UIDocumentPickerViewController with allowsMultipleSelection = false.
Tap quickly on the same file in the picker 2 times.
Result: Both the document picker and the presenting view controller are dismissed.
Reproducible Code Snippet
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
addLabel("Parent View Controller")
DispatchQueue.main.async { [unowned self] in
let child = UIViewController()
child.view.backgroundColor = .yellow
present(child, animated: true)
child.addLabel("Child View Controller")
let vc = UIDocumentPickerViewController(
forOpeningContentTypes: [.pdf, .jpeg, .png],
asCopy: true
)
vc.allowsMultipleSelection = false
child.present(vc, animated: true)
}
}
}
extension UIViewController {
func addLabel(_ text: String) {
let label = UILabel(frame: CGRect(x: 0, y: 50, width: view.bounds.width, height: 30))
label.text = text
view.addSubview(label)
}
}
Environment
Device: iPhone 15 Pro and others
iOS version: 18.2 (reproduces on multiple iOS versions)
Occurs with: .pdf, .jpeg, .png file types
Mode: Both simulator and real device
Notes
Happens consistently with fast multiple taps on the same file.
This breaks expected view controller stack behavior.
My app inputs electrical waveforms from an IV485B39 2 channel USB device using an AVAudioSession. Before attempting to acquire data I make sure the input device is available as follows:
AVAudiosSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory :AVAudioSessionCategoryRecord error:&err];
NSArray *inputs = [audioSession availableInputs];
I have been using this code for about 10 years.
My app is scriptable so a user can acquire data from the IV485B29 multiple times with various parameter settings (sampling rates and sample duration). Recently the scripts have been failing to complete and what I have notice that when it fails the list of available inputs is missing the USBAudio input. While debugging I have noticed that when working properly the list of inputs includes both the internal microphone as well as the USBAudio device as shown below.
VIB_TimeSeriesViewController:***Available inputs = (
"<AVAudioSessionPortDescription: 0x11584c7d0, type = MicrophoneBuiltIn; name = iPad Microphone; UID = Built-In Microphone; selectedDataSource = Front>",
"<AVAudioSessionPortDescription: 0x11584cae0, type = USBAudio; name = 485B39 200095708064650803073200616; UID = AppleUSBAudioEngine:Digiducer.com :485B39 200095708064650803073200616:000957 200095708064650803073200616:1; selectedDataSource = (null)>"
)
But when it fails I only see the built in microphone.
VIB_TimeSeriesViewController:***Available inputs = (
"<AVAudioSessionPortDescription: 0x11584cef0, type = MicrophoneBuiltIn; name = iPad Microphone; UID = Built-In Microphone; selectedDataSource = Front>"
)
If I only see the built in microphone I immediately repeat the three lines of code and most of the "inputs" contains both the internal microphone and the USBAudioDevice
AVAudiosSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory :AVAudioSessionCategoryRecord error:&err];
NSArray *inputs = [audioSession availableInputs];
This fix always works on my M2 iPadPro and my iPhone 14 but some of my customers have older devices and even with 3 tries they still get faults about 1 in 10 tries.
I rolled back my code to a released version from about 12 months ago where I know we never had this problem and compiled it against the current libraries and the problem still exists. I assume this is a problem caused by a change in the AVAudioSession framework libraries. I need to find a way to work around the issue or get the library fixed.
I have a grid setup where I'm displaying multiple images which is working fine. Images are ordered by the date they're added, newest to oldest.
I'm trying to set it up so that the user can change the sort order themselves but am having trouble getting the view to update.
I'm setting the fetch request using oldest to newest as default when initialising the view, then when its appears updating the sort descriptor
struct ProjectImagesListView: View {
@Environment(\.managedObjectContext) private var viewContext
var project : Project
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
@FetchRequest var pictures: FetchedResults<Picture>
var body: some View {
ScrollView {
LazyVGrid(columns: columns) {
ForEach(pictures) { picture in
NavigationLink(destination: ProjectImageDetailView(picture: picture)) {
if let pictureData = picture.pictureThumbnailData, let uiImage = UIImage(data: pictureData) {
Image(uiImage: uiImage)
.resizable()
.scaledToFit()
.frame(height: 100)
} else {
Image("missing")
.resizable()
.scaledToFit()
.frame(height: 100)
}
}
}
}
}
.navigationBarTitle("\(project.name ?? "") Images", displayMode: .inline)
.onAppear() {
guard let sortOrder = getSettingForPhotoOrder() else { return }
guard let sortOrderValue = sortOrder.settingValue else { return }
NSLog("sortOrderPhotos: \(String(describing: sortOrder.settingValue))")
if sortOrderValue == "Newest" {
NSLog("sortOrderPhotos: Change from default")
let newSortDescriptor = NSSortDescriptor(keyPath: \Picture.dateTaken, ascending: false)
pictures.nsSortDescriptors = [newSortDescriptor]
}
}
}
func getSettingForPhotoOrder() -> Setting? {
let fetchRequest: NSFetchRequest<Setting> = Setting.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "name = %@", "photoSortOrder")
fetchRequest.fetchLimit = 1
do {
let results = try viewContext.fetch(fetchRequest)
return results.first
} catch {
print("Fetching Failed")
}
return nil
}
init(project: Project) {
self.project = project
_pictures = FetchRequest(
entity: Picture.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Picture.dateTaken, ascending: true)
],
predicate: NSPredicate(format: "project == %@", project)
)
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
SwiftUI, using LPLinkView through UIViewRepresentable. Default behavior is a long press brings up a context menu and a popover to preview content. I want to replace that default long press behavior with my own custom screen. Adding a UILongPressGestureRecognizer didn't work.
Thanks!
I think it can be dismissed with dismiss() onInAppPurchaseCompletion action handler but I have no reason to handle it, and if it's not handled it will show error alerts for you (see documentation).
How can I dismiss it and still benefit from default onInAppPurchaseCompletion action?
Thanks,