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.

All subtopics
Posts under UI Frameworks topic

Post

Replies

Boosts

Views

Activity

How to Programmatically Simulate a Button Tap in SwiftUI?
In UIKit, certain events like a button tap can be simulated using: button.sendActions(for: .touchUpInside) This allows us to trigger the button’s action programmatically. However, in SwiftUI, there is no direct equivalent of sendActions(for:) for views like Button. What is the recommended approach to programmatically simulate a SwiftUI button tap and trigger its action? Is there an alternative mechanism to achieve this(and for other events under UIControl.event) , especially in scenarios where we want to test interactions or trigger actions without direct user input?
1
0
399
Mar ’25
Performing simulations in the UI elements in uikit
I wanted to perform simulation in my application as a self tour guide for my user. For this I want to programatically simulate various user interaction events like button click, keypress event in the UITextField or moving the cursor around in the textField. These are only few examples to state, it can be any user interaction event or other events. I wanted to know what is the apple recommendation on how should these simulations be performed? Is there something that apple offers like creating an event which can be directly executed for simulations. Is there some library available for this purpose?
Topic: UI Frameworks SubTopic: UIKit Tags:
2
0
317
Feb ’25
SwiftUI List DisclosureGroup Rendering Issues on macOS 13 & 14
Issue Description Whenever the first item in the List is a DisclosureGroup, all subsequent disclosure groups work fine. However, if the first item is not a disclosure group, the disclosure groups in subsequent items do not render correctly. This issue does not occur in macOS 15, where everything works as expected. Has anyone else encountered this behavior, or does anyone have a workaround for macOS 13 & 14? I’m not using OutlineGroup because I need to bind to an isExpanded property for each row in the list. Reproduction Steps I’ve created a small test project to illustrate the issue: Press “Insert item at top” to add a non-disclosure item at the start of the list. Then, press “Append item with sub-item” to add a disclosure group further down. The disclosure group does not display correctly. The label of the disclosure group renders fine, but the content of the disclosure group does not display at all. Press "Insert item at top with sub-item" and the list displays as expected. Build Environment macOS 15.3.2 (24D81) Xcode Version 16.2 (16C5032a) Issue Observed macOS 13 & 14 (bug occurs) macOS 15 (works correctly) Sample Code import SwiftUI class ListItem: ObservableObject, Hashable, Identifiable { var id = UUID() @Published var name: String @Published var subItems: [ListItem]? @Published var isExpanded: Bool = true init( name: String, subjobs: [ListItem]? = nil ) { self.name = name self.subItems = subjobs } static func == (lhs: ListItem, rhs: ListItem) -> Bool { lhs.id == rhs.id } func hash(into hasher: inout Hasher) { hasher.combine(id) } } struct ContentView: View { @State private var listItems: [ListItem] = [] @State private var selectedJob: ListItem? @State private var redraw: Int = 0 var body: some View { VStack { List(selection: $selectedJob) { ForEach(self.listItems, id: \.id) { job in self.itemRowView(for: job) } } .id(redraw) Button("Insert item at top") { self.listItems.insert( ListItem( name: "List item \(listItems.count)" ), at: 0 ) } Button("Insert item at top with sub-item") { self.listItems.insert( ListItem( name: "List item \(listItems.count)", subjobs: [ListItem(name: "Sub-item")] ), at: 0 ) } Button("Append item") { self.listItems.append( ListItem( name: "List item \(listItems.count)" ) ) } Button("Append item with sub-item") { self.listItems.append( ListItem( name: "List item \(listItems.count)", subjobs: [ListItem(name: "Sub-item")] ) ) } Button("Clear") { self.listItems.removeAll() } Button("Redraw") { self.redraw += 1 } } } @ViewBuilder private func itemRowView(for job: ListItem) -> some View { if job.subItems == nil { self.itemLabelView(for: job) } else { AnyView( erasing: ListItemDisclosureGroup(job: job) { self.itemLabelView(for: job) } jobRowView: { child in self.itemRowView(for: child) } ) } } @ViewBuilder private func itemLabelView(for job: ListItem) -> some View { Text(job.name) } struct ListItemDisclosureGroup<LabelView: View, RowView: View>: View { @ObservedObject var job: ListItem @ViewBuilder let labelView: () -> LabelView @ViewBuilder let jobRowView: (ListItem) -> RowView var body: some View { DisclosureGroup(isExpanded: $job.isExpanded) { if let children = job.subItems { ForEach(children, id: \.id) { child in self.jobRowView(child) } } } label: { self.labelView() } } } }
1
0
75
Mar ’25
Crash using Binding.init?(_: Binding<Value?>)
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
2
0
291
Mar ’25
How do we pass a selected item to a sheet?
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
3
0
243
Mar ’25
Uikit : -[UIApplication _terminateWithStatus:] + 136 (UIApplication.m:7539)
I have a few crash report from TestFlight with this context and nothing else. No symbols of my application. Crash report is attached. crashlog.crash It crashes at 16H25 (local time paris) and a few minutes after (8) I see the same user doing task in background (they download data with a particular URL in BGtasks) with a Delay that is consistant with a background wait of 5 or 7 minutes. I have no more information on this crash and by the way Xcode refuses to load it and shows an error. ( I did a report via Xcode for this).
0
0
75
Mar ’25
.fileImporter not working on iPhone
I've been running into an issue using .fileImporter in SwiftUI already for a year. On iPhone simulator, Mac Catalyst and real iPad it works as expected, but when it comes to the test on a real iPhone, the picker just won't let you select files. It's not the permission issue, the sheet won't close at all and the callback isn't called. At the same time, if you use UIKits DocumentPickerViewController, everything starts working as expected, on Mac Catalyst/Simulator/iPad as well as on a real iPhone. Steps to reproduce: Create a new Xcode project using SwiftUI. Paste following code: import SwiftUI struct ContentView: View { @State var sShowing = false @State var uShowing = false @State var showAlert = false @State var alertText = "" var body: some View { VStack { VStack { Button("Test SWIFTUI") { sShowing = true } } .fileImporter(isPresented: $sShowing, allowedContentTypes: [.item]) {result in alertText = String(describing: result) showAlert = true } VStack { Button("Test UIKIT") { uShowing = true } } .sheet(isPresented: $uShowing) { DocumentPicker(contentTypes: [.item]) {url in alertText = String(describing: url) showAlert = true } } .padding(.top, 50) } .padding() .alert(isPresented: $showAlert) { Alert(title: Text("Result"), message: Text(alertText)) } } } DocumentPicker.swift: import SwiftUI import UniformTypeIdentifiers struct DocumentPicker: UIViewControllerRepresentable { let contentTypes: [UTType] let onPicked: (URL) -> Void func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIViewController(context: Context) -> UIDocumentPickerViewController { let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: contentTypes, asCopy: true) documentPicker.delegate = context.coordinator documentPicker.modalPresentationStyle = .formSheet return documentPicker } func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {} class Coordinator: NSObject, UIDocumentPickerDelegate { var parent: DocumentPicker init(_ parent: DocumentPicker) { self.parent = parent } func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { print("Success!", urls) guard let url = urls.first else { return } parent.onPicked(url) } func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { print("Picker was cancelled") } } } Run the project on Mac Catalyst to confirm it working. Try it out on a real iPhone. For some reason, I can't attach a video, so I can only show a screenshot
1
0
459
Feb ’25
Regarding errors with UIToolbar and UIBarButtonItem set to UITextField
I set UIToolbar and UIBarButtonItem to UITextField placed on Xib, but when I run it on iOS18 iPad, the following error is output to Xcode Console, and UIPickerView set to UITextField.inputView is not displayed. Error: this application, or a library it uses, has passed an invalid numeric value (NaN, or not-a-number) to CoreGraphics API and this value is being ignored. Please fix this problem. If you want to see the backtrace, please set CG_NUMERICS_SHOW_BACKTRACE environmental variable. Backtrace: <CGPathAddLineToPoint+71> <+[UIBezierPath _continuousRoundedRectBezierPath:withRoundedCorners:cornerRadii:segments:smoothPillShapes:clampCornerRadii:] <+[UIBezierPath _continuousRoundedRectBezierPath:withRoundedCorners:cornerRadius:segments:]+175> <+[UIBezierPath _roundedRectBezierPath:withRoundedCorners:cornerRadius:segments:legacyCorners:]+338> <-[_UITextMagnifiedLoupeView layoutSubviews]+2233> <__56-[_UITextMagnifiedLoupeView _updateCloseLoupeAnimation:]_block_invoke+89> <+[UIView(UIViewAnimationWithBlocksPrivate) _modifyAnimationsWithPreferredFrameRateRange:updateReason:animations:]+166> <block_destroy_helper.269+92> <block_destroy_helper.269+92> <__swift_instantiateConcreteTypeFromMangledName+94289> <block_destroy_helper.269+126> <+[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:anima <block_destroy_helper.269+6763> <block_destroy_helper.269+10907> <-[_UITextMagnifiedLoupeView _updateCloseLoupeAnimation:]+389> <-[_UITextMagnifiedLoupeView setVisible:animated:completion:]+256> <-[UITextLoupeSession _invalidateAnimated:]+329> <-[UITextRefinementTouchBehavior textLoupeInteraction:gestureChangedWithState:location:translation:velocity: <-[UITextRefinementInteraction loupeGestureWithState:location:translation:velocity:modifierFlags:shouldCanc <-[UITextRefinementInteraction loupeGesture:]+701> <-[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:]+71> <_UIGestureRecognizerSendTargetActions+100> <_UIGestureRecognizerSendActions+306> <-[UIGestureRecognizer _updateGestureForActiveEvents]+704> <_UIGestureEnvironmentUpdate+3892> <-[UIGestureEnvironment _updateForEvent:window:]+847> <-[UIWindow sendEvent:]+4937> <-[UIApplication sendEvent:]+525> <__dispatchPreprocessedEventFromEventQueue+1436> <__processEventQueue+8610> <updateCycleEntry+151> <_UIUpdateSequenceRun+55> <schedulerStepScheduledMainSection+165> <runloopSourceCallback+68> <__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__+17> <__CFRunLoopDoSource0+157> <__CFRunLoopDoSources0+293> <__CFRunLoopRun+960> <CFRunLoopRunSpecific+550> <GSEventRunModal+137> <-[UIApplication _run]+875> <UIApplicationMain+123> <__debug_main_executable_dylib_entry_point+63> 10d702478 204e57345 Type: Error | Timestamp: 2025-03-09 00:22:46.121407+09:00 | Process: FurusatoLocalCurrency | Library: CoreGraphics | Subsystem: com.apple.coregraphics | Category: Unknown process name | TID: 0x5c360 Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x600002202a30 h=--& v=--& _UIToolbarContentView:0x7fc2c6a5b8f0.width == 0 (active)>", "<NSLayoutConstraint:0x600002175e00 H:|-(0)-[_UIButtonBarStackView:0x7fc2c6817b10] (active, names: '|':_UIToolbarContentView:0x7fc2c6a5b8f0 )>", "<NSLayoutConstraint:0x600002175e50 H:[_UIButtonBarStackView:0x7fc2c6817b10]-(0)-| (active, names: '|':_UIToolbarContentView:0x7fc2c6a5b8f0 )>", "<NSLayoutConstraint:0x6000022019f0 'TB_Leading_Leading' H:|-(8)-[_UIModernBarButton:0x7fc2a5aa8920] (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>", "<NSLayoutConstraint:0x600002201a40 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x7fc2a5aa8920]-(0)-| (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>", "<NSLayoutConstraint:0x600002201e50 'UISV-canvas-connection' UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'.leading == _UIButtonBarButton:0x7fc2f57117f0.leading (active)>", "<NSLayoutConstraint:0x600002201ea0 'UISV-canvas-connection' UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'.trailing == UIView:0x7fc2a5aac8e0.trailing (active)>", "<NSLayoutConstraint:0x6000022021c0 'UISV-spacing' H:[_UIButtonBarButton:0x7fc2f57117f0]-(0)-[UIView:0x7fc2a5aa8330] (active)>", "<NSLayoutConstraint:0x600002202210 'UISV-spacing' H:[UIView:0x7fc2a5aa8330]-(0)-[_UIButtonBarButton:0x7fc2a5aa84d0] (active)>", "<NSLayoutConstraint:0x600002202260 'UISV-spacing' H:[_UIButtonBarButton:0x7fc2a5aa84d0]-(0)-[UIView:0x7fc2a5aac8e0] (active)>", "<NSLayoutConstraint:0x600002176f30 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'](LTR) (active, names: '|':_UIButtonBarStackView:0x7fc2c6817b10 )>", "<NSLayoutConstraint:0x600002176e40 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide']-(0)-|(LTR) (active, names: '|':_UIButtonBarStackView:0x7fc2c6817b10 )>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x600002201a40 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x7fc2a5aa8920]-(0)-| (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
113
Mar ’25
SwiftUI: How do you do CoreData backup and restore?
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
0
0
249
Mar ’25
SwiftUI tvOS NavigationTransition and matchedTransitionSource
According to the docs tvOS 18+ supports the new NavigationTransition and the matchedTransitionSource and navigationTransition(.zoom(sourceID: id, in: namespace)) modifiers, however they don't seems to work. Taking the DestinationVideo project example from the latest WWDC the matchedTransitionSourceis marked with #if os(iOS) Is it supported by tvOS or is it for iOS only? https://developer.apple.com/documentation/swiftui/view/navigationtransition(_:) https://developer.apple.com/documentation/swiftui/view/matchedtransitionsource(id:in:configuration:)
2
0
61
Apr ’25
Alerts/formsheets add 0.8 alpha tint to all vcs all views underneath!?!?!
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
1
0
151
Mar ’25
Picker with inline style on tvOS 18
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.
2
0
80
Mar ’25
app crashing in iPad Only
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
Topic: UI Frameworks SubTopic: UIKit Tags:
1
0
411
Mar ’25
Bumpy navigation animation on back button
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) } }
2
0
70
Mar ’25
SwiftUI: Sheet presented from List row is not removed from screen when row is removed
I noticed if I show a sheet from a List row, then remove the row the sheet isn't removed from the screen like it is if using VStack or LazyVStack. I'd be interested to know the reason why the sheet isn't removed from the screen in the code below. It only occurs with List/Form. VStack/LazyVStack gives the expected result. I was wondering if it is an implementation issue, e.g. since List is backed by UICollectionView maybe the cells can't be the presenter of the sheet for some reason. Launch on iPhone 16 Pro Simulator iOS 18.2 Tap "Show Button" Tap "Show Sheet" What is expected: The sheet should disappear after 5 seconds. And I don't mean it should dismiss, I just mean removed from the screen. Similarly if the View that showed the sheet was re-added and its show @State was still true, then the sheet would be added back to the screen instantly without presentation animation. What actually happens: Sheet remains on screen despite the row that presented the sheet being removed. Xcode 16.2 iOS Simulator 18.2. struct ContentView: View { @State var showButton = false var body: some View { Button("\(showButton ? "Hide" : "Show" ) Button") { showButton = true Task { try? await Task.sleep(for: .seconds(5)) self.showButton = false } } //LazyVStack { // does not have this problem List { if showButton { SheetButton() } } } } struct SheetButton: View { @State var sheet = false @State var counter = 0 var body: some View { Text(counter, format: .number) Button("\(sheet ? "Hide" : "Show") Sheet") { counter += 1 sheet.toggle() } .sheet(isPresented: $sheet) { Text("Wait... This should auto-hide in 5 secs. Does not with List but does with LazyVStack.") Button("Hide") { sheet = false } .presentationDetents([.fraction(0.3)]) } // .onDisappear { sheet = false } // workaround } } I can work around the problem with .onDisappear { sheet = false } but I would prefer the behaviour to be consistent across the container controls.
2
0
396
Feb ’25
SwiftUI: How to change `contentInset` of `List`
Hi, Is there any way of changing the contentInset (UIKit variant) of a List in SwiftUI? I do not see any APIs for doing so, the closest I gotten is to use safeAreaInset . While visually that works the UX is broken as you can no longer "scroll" from the gap made by the .safeAreaInset(edge:alignment:spacing:content:) I have subbmited a feedback suggestion: FB16866956
0
0
182
Mar ’25
NavigationSplitView and NavigationPaths
A NavigationStack with a singular enum for .navigationDestination() works fine. Both NavigationLinks(value:) and directly manipulating the NavigationPath work fine for moving around views. Zero problems. The issue is when we instead use a NavigationSplitView, I've only dabbled with two-column splits (sidebar and detail) so far. Now, if the sidebar has its own NavigationStack, everything works nicely on an iPhone, but on an iPad, you can't push views onto the detail from the sidebar. (They're pushed on the sidebar) You can solve this by keeping a NavigationStack ONLY on the detail. Sidebar links now properly push onto the detail, and the detail can move around views by itself. However, if you mix NavigationLink(value:) with manually changing NavigationPath, it stops working with no error. If you only use links, you're good, if you only change the NavigationPath you're good. Mixing doesn't work. No error in the console either, the breakpoints hit .navigationDestination and the view is returned, but never piled up. (Further attempts do show the NavigationPath is being changed properly, but views aren't changing) This problem didn't happen when just staying on NavigationStack without a NavigationSplitView. Why mix? There's a few reasons to do so. NavigationLinks put the appropriate disclosure indicator (can't replicate its look 100% without it), while NavigationPaths let you trigger navigation without user input (.onChange, etc) Any insights here? I'd put some code samples but there's a metric ton of options I've tested here.
0
0
203
Mar ’25
Buttons in menu don't respect the environment value of .layoutDirection in SwiftUI
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) } }
4
0
88
Mar ’25