Hello everyone,
I've run into a peculiar behavior with UINavigationController's setViewControllers on iOS 18.2 (I guess it might be reproducible on older versions) when reordering view controllers, and I wonder if anyone can shed some light on this issue.
Initial State: The navigation stack is [A - B - C].
Without Animation: Setting [A - C - B] updates the stack to: A - C - B as expected.
With Animation: Using the same command with animation changes the stack to [A - B], oddly omitting C.
Has anyone else noticed similar behavior or knows why animations might disrupt the stack's update this way? I'd appreciate any insights or suggestions.
Thanks, Dmytro
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
In the example code below:
OuterView has a @State var number: Int? = 0
InnerView expects a binding of type Int.
OuterView uses Binding.init(_: Binding<Value?>) to convert from Binding<Int?> to Binding<Int>?.
If OuterView sets number to nil, there is a runtime crash:
BindingOperations.ForceUnwrapping.get(base:) + 160
InnerView is being evaluated (executing body?) when number is nil despite the fact that it shouldn't exist in that configuration. Is this a bug or expected behavior?
struct OuterView: View {
@State var number: Int? = 1
var body: some View {
if let binding = Binding($number) {
InnerView(number: binding)
}
Button("Doesn't Crash") { number = 0 }
Button("Crashes") { number = nil }
}
}
struct InnerView: View {
@Binding var number: Int
var body: some View {
Text(number.formatted())
}
}
There is a workaround that involves adding an extension to Optional<Int>:
extension Optional<Int> {
var nonOptional: Int {
get { self ?? 0 }
set { self = newValue }
}
}
And using that to ensure that the binding has a some value even when number is nil.
if number != nil {
InnerView(number: $number.nonOptional)
}
This works, but I don't understand why it's necessary. Any insight would be greatly appreciated!
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hi,
Previously, we would conform model objects to the ObservableObject protocol and use the @StateObject property wrapper when storing them to an owned binding in a View.
Now, if I understand correctly, it is recommended that we use the new @Observable macro/protocol in place of ObservableObject and use the @State property wrapper rather than @StateObject. This is my understanding from documentation articles such as Migrating from the Observable Object protocol to the Observable macro.
However, the StateObject property wrapper has an initialiser which takes an autoclosure parameter:
extension StateObject {
public init(wrappedValue thunk: @autoclosure @escaping () -> ObjectType)
}
This is an extremely important initialiser for state objects that are expensive to allocate. As far as I can tell, the @State property wrapper lacks an equivalent initialiser.
What is the recommended migration strategy for objects which made use of this on StateObject?
Thanks
I have view showing a list of contacts. When the user taps one, I want to raise a sheet that shows the contact's phone numbers and E-mail addresses and lets the user pick one.
When the user taps a list entry, I store the associated Contact object into a @State variable called selectedContact. Then I set the boolean that's bound to the sheet modifier's isPresented flag. That modifier:
.sheet(isPresented: $showContactMethodSheet, content: { ContactMethodView(withContact: selectedContact!) })
But the app crashes, because despite selectedContact having been set. It looks like the sheet was pre-built with a nil selected contact upon view load. Why, and what is the expected approach here?
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hello!
After upgrading to Xcode 16 & Swift 6 & iOS 18 I starting receiveing strange crashes.
Happens randomly in different view and pointing to onGeometryChange action block. I added DispatchQueue.main.async { in hopes it will help but it didn't.
HStack {
...
}
.onGeometryChange(for: CGSize.self, of: \.size) { value in
DispatchQueue.main.async {
self.width = value.width
self.height = value.height
}
}
As far as I understand, onGeometryChange is defined as nonisolated and Swift 6 enforce thread checking for the closures, SwiftUI views are always run on the main thread. Does it mean we can not use onGeometryChange safely in swiftui?
BUG IN CLIENT OF LIBDISPATCH: Assertion failed: Block was expected to execute on queue [com.apple.main-thread (0x1eacdce40)]
Crashed: com.apple.SwiftUI.AsyncRenderer
0 libdispatch.dylib 0x64d8 _dispatch_assert_queue_fail + 120
1 libdispatch.dylib 0x6460 _dispatch_assert_queue_fail + 194
2 libswift_Concurrency.dylib 0x62b58 <redacted> + 284
3 Grit 0x3a57cc specialized implicit closure #1 in closure #1 in PurchaseModalOld.body.getter + 4377696204 (<compiler-generated>:4377696204)
4 SwiftUI 0x5841e0 <redacted> + 60
5 SwiftUI 0x5837f8 <redacted> + 20
6 SwiftUI 0x586b5c <redacted> + 84
7 SwiftUICore 0x68846c <redacted> + 48
8 SwiftUICore 0x686dd4 <redacted> + 16
9 SwiftUICore 0x6ecc74 <redacted> + 160
10 SwiftUICore 0x686224 <redacted> + 872
11 SwiftUICore 0x685e24 $s14AttributeGraph12StatefulRuleP7SwiftUIE15withObservation2doqd__qd__yKXE_tKlF + 72
12 SwiftUI 0x95450 <redacted> + 1392
13 SwiftUI 0x7e438 <redacted> + 32
14 AttributeGraph 0x952c AG::Graph::UpdateStack::update() + 540
15 AttributeGraph 0x90f0 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 424
16 AttributeGraph 0x8cc4 AG::Subgraph::update(unsigned int) + 848
17 SwiftUICore 0x9eda58 <redacted> + 348
18 SwiftUICore 0x9edf70 <redacted> + 36
19 AttributeGraph 0x148c0 AGGraphWithMainThreadHandler + 60
20 SwiftUICore 0x9e7834 $s7SwiftUI9ViewGraphC18updateOutputsAsync2atAA11DisplayListV4list_AG7VersionV7versiontSgAA4TimeV_tF + 560
21 SwiftUICore 0x9e0fc0 $s7SwiftUI16ViewRendererHostPAAE11renderAsync8interval15targetTimestampAA4TimeVSgSd_AItF + 524
22 SwiftUI 0xecfdfc <redacted> + 220
23 SwiftUI 0x55c84 <redacted> + 312
24 SwiftUI 0x55b20 <redacted> + 60
25 QuartzCore 0xc7078 <redacted> + 48
26 QuartzCore 0xc52b4 <redacted> + 884
27 QuartzCore 0xc5cb4 <redacted> + 456
28 CoreFoundation 0x555dc <redacted> + 176
29 CoreFoundation 0x55518 <redacted> + 60
30 CoreFoundation 0x55438 <redacted> + 524
31 CoreFoundation 0x54284 <redacted> + 2248
32 CoreFoundation 0x535b8 CFRunLoopRunSpecific + 572
33 Foundation 0xb6f00 <redacted> + 212
34 Foundation 0xb6dd4 <redacted> + 64
35 SwiftUI 0x38bc80 <redacted> + 792
36 SwiftUI 0x1395d0 <redacted> + 72
37 Foundation 0xc8058 <redacted> + 724
38 libsystem_pthread.dylib 0x637c _pthread_start + 136
39 libsystem_pthread.dylib 0x1494 thread_start + 8
I set the titleView of a view controller to a UISlider like so in viewDidLoad:
UISlider *slider = [UISlider new];
self.navigationItem.titleView = slider;
The desired outcome is that the slider takes the full width of the title view. This is working fine when the view is loaded in the wider landscape mode. The slider adjust its size as expected when rotating to portrait mode.
However, when the view is loaded in the narrower portrait mode and then the device is rotated to landscape, the slider does not grow in width to make use of the newly available size.
Why is that so and how can it get the desired outcome as described?
After viewDidLoad:
After rotating:
So I am looking to use a custom NSWindow application (so I can implement some enhanced resizing/dragging behavior which is only possible overriding NSWindow).
The problem is my whole application is currently SwiftUI-based (see the project here: https://github.com/msdrigg/Roam/blob/50a2a641aa5f2fccb4382e14dbb410c1679d8b0c/Roam/RoamApp.swift).
I know there is a way to make this work by dropping my @main SwiftUI app and replacing it with a SwiftUI root view hosted in a standard AppKit root app, but that feels like I'm going backwards.
Is there another way to get access (and override) the root NSWindow for a SwiftUI app?
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
Hello, I have the following code:
struct SettingsButton: View {
var action: () -> Void
@State private var rotate: Bool = false
var body: some View {
Button(action: {
rotate.toggle()
action()
}, label: {
Image(systemName: "gearshape")
})
.symbolEffect(.rotate, value: rotate)
}
}
For some reason, my button is not rotating. Other effects such as pulse and bounce work as expected. I applied the .clockwise direction thinking it needed a direction set, but that didn't work either. I also tried using the symbolEffect with isActive, and that didn't work. Lastly, I thought there may be an issue with Xcode so I closed that and reopened, but still not working.
Any ideas?
Hello,
I just noticed weird unexpected behaviour.
It seems when you present UIAlertController or custom VC as partially screen covering formsheet, ALL the views underneath get 0.8 alpha tint (ios 15 and 18)
Is there any way to disable this behaviour?
So far it only breaks minor custom "star" view but I imagine arbitrarily adding 0.8 alpha to EVERYTHING can really mess up some layouts/designs.
Regards,
Martynas Stanaitis
Topic:
UI Frameworks
SubTopic:
UIKit
I have a SwiftUI List (on macOS) where I want to display a few TextFields in each row, and observe how the focus changes as an individual text field is selected or unselected. This seems to work fine if I just have the List display a pure TextField in each row, but if I embed the TextField inside a Button view, the focus change notifications stop working. I want the 'button' functionality so that the user can tap anywhere on the row and have the text field activated, instead of tapping exactly on the text field boundary.
Here is some code to demonstrate the problem. In the List if you have RowView uncommented out (1), then the focus change notifications work. If you comment that out and uncomment the RowViewWithButton (2), then the button functionality works, but I can't get focus change notifications anymore.
Here is the code to reproduce the issue. Interestingly, when I test this on iOS, it works fine in both cases. But I need the solution for macOS.
import SwiftUI
// test on macOS target
struct ContentView: View {
@State private var textFields = Array(repeating: "", count: 4)
@FocusState private var focusedField: Int?
var body: some View {
List(0..<4, id: \.self) { index in
// 1. works with focus notification changes
RowView(index: index, text: $textFields[index], focusedField: $focusedField)
// 2. button works, but no focus notifications on text field
//RowViewWithButton(index: index, text: $textFields[index], focusedField: $focusedField)
}
}
}
struct RowView: View {
let index: Int
@Binding var text: String
@FocusState.Binding var focusedField: Int?
var body: some View {
HStack {
Text("Row \(index + 1):")
TextField("", text: $text)
.multilineTextAlignment(.leading)
.focused($focusedField, equals: index)
}
.onChange(of: focusedField) { newFocus in
if newFocus == index {
print("TextField \(index) is in focus")
} else {
print("TextField \(index) lost focus")
}
}
.padding(.vertical, 4)
}
}
struct RowViewWithButton: View {
let index: Int
@Binding var text: String
@FocusState.Binding var focusedField: Int?
var body: some View {
Button (action: {
print("RowView - button selected at index \(index)")
focusedField = index
}) {
HStack {
Text("Row \(index + 1):")
TextField("", text: $text)
.multilineTextAlignment(.leading)
.focused($focusedField, equals: index)
}
.onChange(of: focusedField) { newFocus in
if newFocus == index {
print("TextField \(index) is in focus")
} else {
print("TextField \(index) lost focus")
}
}
.foregroundColor(.primary)
}
.buttonStyle(BorderlessButtonStyle())
.padding(.vertical, 4)
}
}
#Preview {
ContentView()
.frame(width: 320, height: 250)
}
app crashing in iPad Only and not getting help from logs
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x000000016d667fd0
Exception Codes: 0x0000000000000002, 0x000000016d667fd0
VM Region Info: 0x16d667fd0 is in 0x16d664000-0x16d668000; bytes after start: 16336 bytes before end: 47
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
MALLOC_SMALL 132c00000-133000000 [ 4096K] rw-/rwx SM=PRV
GAP OF 0x3a664000 BYTES
---> STACK GUARD 16d664000-16d668000 [ 16K] ---/rwx SM=NUL stack guard for thread 0
Stack 16d668000-16d764000 [ 1008K] rw-/rwx SM=SHM thread 0
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [10927]
Triggered by Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 UIKitCore 0x186fae04c __66-[UITraitCollection _traitCollectionByModifyingTraitsCopyOnWrite:]_block_invoke_2 + 4
1 UIKitCore 0x186faefdc __54-[UITraitCollection traitCollectionByModifyingTraits:]_block_invoke + 36
2 UIKitCore 0x186fabfc8 -[UITraitCollection _traitCollectionByModifyingTraitsCopyOnWrite:] + 252
3 UIKitCore 0x187109b08 -[UITraitCollection traitCollectionByModifyingTraits:] + 120
4 UIKitCore 0x1871c013c -[UIScreen _defaultTraitCollectionForInterfaceOrientation:inBounds:] + 224
5 UIKitCore 0x1871bff8c -[UIApplication _isOrientationVerticallyCompact:] + 48
6 UIKitCore 0x1871bcd28 -[UIApplication _isStatusBarHiddenForOrientation:] + 24
7 UIKitCore 0x186fe0d10 +[UIWindow(StatusBarManager) _prefersStatusBarHiddenInWindow:targetOrientation:animationProvider:] + 260
8 UIKitCore 0x186fe310c +[UIWindow(StatusBarManager) _prefersStatusBarHiddenInWindow:animationProvider:] + 72
9 UIKitCore 0x186fe2e00 -[UIApplication _isStatusBarEffectivelyHiddenForContentOverlayInsetsForWindow:] + 132
10 UIKitCore 0x186fe0a9c -[UIWindow _sceneSafeAreaInsetsIncludingStatusBar:] + 184
11 UIKitCore 0x187037628 -[UIWindow _normalizedSafeAreaInsets] + 64
12 UIKitCore 0x1870375a0 -[UIWindow safeAreaInsets] + 76
13 UIKitCore 0x186fa6c70 -[UIView _updateSafeAreaInsets] + 68
14 UIKitCore 0x188529824 -[UIView _recursiveEagerlyUpdateSafeAreaInsetsUntilViewController] + 176
It has been asked several times in the forum, but apple has always maintained that screenshot capture prevention is not supported, how is it that whatsapp and several financial apps are doing it, if screenshot capturing is not possible, its not DRM, is it the adding of a secured text as a layer on to the uiview layer? how have they designed a custom screen if that is the case? Also how is it getting approved by apple! If detection of airplay is possible and can be suppressed, why not screenshot?
Xcode 16 iOS18 WKWebView里包含http图片时无法显示
Topic:
UI Frameworks
SubTopic:
UIKit
WKWebView cannot load and display HTTP image resources
Topic:
UI Frameworks
SubTopic:
UIKit
Hello all,
In a SwiftUI List, when a row is selected, a blue selection is drawn in the selection, and foreground Text with the default primary color is automatically made white. For other views with custom colors, I'd like to be able to make sure they become tinted white to match the system apps. For example, see the blue dot on the selected row:
Example code:
List(selection: $selection) {
ForEach(0..<4) { index in
HStack {
Image(systemName: "circle.fill")
.foregroundColor(.blue)
Text("Test")
}
.tag(index)
}
}
With NSTableCellView, there is the backgroundStyle property. I've searched all of the available environment variables, and couldn't find anything appropriate. I have also tried manually including an isSelected binding on a view for each row, but the selection binding is not updated by List until mouse-up, while the highlight is updated on mouse-down and drag, so this results in a flickery appearance and is not right either.
Any tips on how to achieve the correct result here? Thanks! 🙏
I want to hide some sensitive information when app is visible in the list of process on iOS.
I observed that privacySensitive() modifier is not working for my app in case when view is embedded in UIHostingController.
I works correctly for pure SwiftUI app.
Can someone confirm this?, any workaround to make it working for my case.
We have SwiftUI AttributedString with links. But these links are inaccessible via automation scripts.
The text is visible to the automation scripts as XCUIElementTypeStaticText and there is no provision to access the links within.
Is there any workaround available for this case ?
Topic:
UI Frameworks
SubTopic:
SwiftUI
Is it possible to change the default save dialog that appears when creating a document based MacOS app in SwiftUI?
I have a basic FileDocument struct that gets called to a view using a DocumentGroup scene.
struct MyFile: FileDocument {
static let readableContentTypes: [UTType] = [.myFileType]
static let writeableContentTypes: [UTType] = [.myFileType]
var list: [String]
init(configuration: ReadConfiguration) throws {
let data = configuration.file.regularFileContents!
let JSONDecoder = JSONDecoder()
do {
try list = JSONDecoder.decode([String].self, from: data)
} catch {
throw CocoaError(.fileReadCorruptFile)
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let JSONEncoder = JSONEncoder()
JSONEncoder.outputFormatting = .prettyPrinted
do {
data = try JSONEncoder.encode(self.list)
} catch {
print(error.localizedDescription)
throw CocoaError(.fileWriteUnknown)
}
return .init(regularFileWithContents: data)
}
}
This gets called at the DocumentGroup
DocumentGroup(newDocument: MyFile(), editor: { document in
ContentView(document: document.$document)
})
But when I save the file, I want the save dialog that appears to have something like a 'Tags' textField that can also store information about the file.
Something similar to this: (https://i.sstatic.net/AJQ3YNb8.png)
From what I can find, there isn't much information about this other than manually creating an NSSavePanel class and overriding the current save function
Over the past two weeks, we have noticed widespread degraded performance in iOS devices not recognizing when links are App Clips. When scanning the QR code, it identifies it as a link, not an App Clip link and tries to open the link via Safari. Once in Safari, it still prompts the user to download the full app and not open the App Clip. Scanning with the Control Center "Scan Code" button gives an indication that it understands it's an App Clip link, but still does not open it correctly. In some cases, it will say "App Clip Unavailable" which is simply not true.
After a few scans of the same QR code, the iOS device will correct itself and open the correct App Clip. There is no consistency and/or reason why it would do this.
We have had a massive influx of users complaining that it's not opening the App Clip correctly. We have not changed anything on our website or app that would alter the efficacy of this issue. Have tested on a variety of different iOS devices on a variety of different operating systems (iPads, iPhones, iOS 16, iOS 18, etc) and they all have started behaving this same way. In addition, we've tested on other apps with App Clips and they are experiencing the same issue. My guess is that there is something happening on Apple's side with apple-app-site-association issues.
We reported via Feedback Assistant but have yet to hear from anyone from Apple to acknowledge this is a widespread issue.