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

navigationDestination + NavigationPath broken on iOS 17
Using the new navigationDestination and NavigationPath functions previously on iOS 16 everything has been working fine using a custom back button, which calls path.removeLast(). However, if we try this on iOS 17, the screen being removed flashes white. You can try this code as an example (NOTE THE WHITE FLASH ON REMOVE LAST): struct DetailView: View { @Binding var path: NavigationPath var body: some View { ZStack { Color.black VStack(alignment: .center) { Spacer() Button(action: { path.removeLast() }, label: { Text("BACK") }) Spacer() } } } } struct ParentView: View { @State var path: NavigationPath = .init() var body: some View { NavigationStack(path: $path) { ZStack { Color.red VStack(alignment: .center) { Spacer() Button(action: { path.append("TEST") }, label: { Text("FORWARD") }) Spacer() } } .navigationDestination(for: String.self) { _ in DetailView(path: $path) } } } } Any work arounds? Suggestions?
3
2
1.5k
Sep ’23
Seeking KeyboardLayout ID for All Native Keyboards in iOS and macOS
Hello everyone, I am currently working on a project that requires me to programmatically manage keyboard layouts on both iOS and macOS devices. I'm looking for a comprehensive list of KeyboardLayout ID values for all the native keyboard layouts available in both iOS and macOS. While I can extract some of this information from the /System/Library/Keyboard Layouts/ directory on macOS, I cannot extract all without adding every keyboard layout active, having a complete and pre-compiled list would be immensely helpful. Does anyone here have such a list or know where I might find one? Any guidance on this matter would be greatly appreciated. Thank you in advance for your assistance! JJ
4
0
865
Sep ’23
Unknown Crash - OUTLINED_FUNCTION_2
We've got hundreds of crashes in our SwiftUI app which we think are "silent" crashes as there are no complaints from clients and yet - it happens on the main thread in the foreground so I'm not completely sure. The annoying thing is that we have no idea by the stack trace what is causing this issue, I feel helpless as this is causing some very loud noise through management and honestly - myself who wants to have this noise cleared. this particular crash is the highest impact (one of a few different weird crashes in our app without clear stack trace) 0 SwiftUI 0x895d90 OUTLINED_FUNCTION_2 + 836 1 SwiftUI 0x895da8 OUTLINED_FUNCTION_2 + 860 2 SwiftUI 0x1329880 OUTLINED_FUNCTION_2 + 424 3 SwiftUI 0x6806c OUTLINED_FUNCTION_441 + 584 4 SwiftUI 0x481b0 OUTLINED_FUNCTION_194 + 544 5 UIKitCore 0x1b7194 -[UIViewController removeChildViewController:notifyDidMove:] + 128 6 UIKitCore 0x77d6e8 -[UINavigationController removeChildViewController:notifyDidMove:] + 80 7 UIKitCore 0x205224 -[UIViewController dealloc] + 768 8 UIKitCore 0x1036c -[UINavigationController viewDidDisappear:] + 372 9 UIKitCore 0xd9c4 -[UIViewController _setViewAppearState:isAnimating:] + 1012 10 UIKitCore 0x46e61c -[UIViewController __viewDidDisappear:] + 136 11 UIKitCore 0x7ec024 __64-[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]_block_invoke_3 + 44 12 UIKitCore 0x1a3f24 -[UIViewController _executeAfterAppearanceBlock] + 84 13 UIKitCore 0x1a3e68 -[_UIAfterCACommitBlock run] + 72 14 UIKitCore 0x1a3d9c -[_UIAfterCACommitQueue flush] + 176 15 UIKitCore 0x1a3ca8 _runAfterCACommitDeferredBlocks + 496 16 UIKitCore 0x3f530 _cleanUpAfterCAFlushAndRunDeferredBlocks + 108 17 CoreFoundation 0x43564 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 18 CoreFoundation 0xabd9c __CFRunLoopDoBlocks + 368 19 CoreFoundation 0x7bbbc __CFRunLoopRun + 856 20 CoreFoundation 0x80ed4 CFRunLoopRunSpecific + 612 21 GraphicsServices 0x1368 GSEventRunModal + 164 22 UIKitCore 0x3a23d0 -[UIApplication _run] + 888 23 UIKitCore 0x3a2034 UIApplicationMain + 340 24 SwiftUI 0x1d1014 OUTLINED_FUNCTION_895 + 2420 25 SwiftUI 0x13216c block_copy_helper.1 + 388 26 SwiftUI 0x11b4bc OUTLINED_FUNCTION_901 + 2868 Number 27 will be our app's Main function and that it - no other trace of our apps code. Firebase is saying this happens 100% on iOS 16 only and always on the foreground. How can I get to the bottom of this? how can I debug such a crash?
11
2
3k
Sep ’23
How to support foregroundColor (deprecated) and foregroundStyle in watchOS 9/10?
In my Watch app on watchOS 9 I was using .foregroundColor(myColour) to colour the text in a widgetLabel on a corner complication like this: let myColour: Color = functionThatReturnsAColorObjectConstructedLike Color.init(...) // green .widgetLabel { Text(myText) .foregroundColor(myColour) } It worked fine; the widget label was green. Now, in watchOS 10, I see that foregroundColor() is being deprecated in favour of foregroundStyle(), and I can use .foregroundStyle(.green), and - importantly - foregroundStyle() is only available on watchOS 10 and newer. myColour is calculated depending on some other info, so I can't just write .green, and when I use .foregroundStyle(myColour) the widget label comes out as white every time, even if I set myColour = .green. I think I have to use some sort of extension to pick the right combination, something like: extension View { func foregroundType(colour: Colour, style: any ShapeStyle) -> some THING? { if #available(watchOS 10.0, *) { return foregroundStyle(style) } else { return foregroundColor(colour) } } } // Usage let myStyle: any ShapeStyle = SOMETHING? ... .widgetLabel { Text(myText) .foregroundType(colour: myColour, style: myStyle) It doesn't work. I just can't figure out what should be returned, nor how to return it. Any ideas?
3
2
3.4k
Sep ’23
WatchOS app crashes when using .topBarTrailing toolbar item placement
I'm running into an issue with using .topBarTrailing placement for a toolbar item. The app fails to launch (crashes) with this placement. The following view works fine with any other placement (other than .topBarLeading). What am I doing wrong? var body: some View { NavigationStack { Text("Overview") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button { // noop } label: { Label("Add", systemImage: "plus") } } } .navigationTitle("Overview") .navigationBarTitleDisplayMode(.inline) } } I've opted to use .confirmationAction as a workaround, which works fine. It also positions the toolbar item in the same place on the view as the .topBarTrailing placement would. I'm using Xcode version 15.0 and targeting WatchOS 10. Verbose error output when trying to run the app in the simulator: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Layout requested for visible navigation bar, <PUICStackedNavigationBar: 0x100e1e8d0; baseClass = UINavigationBar; frame = (0 0; 198 60); opaque = NO; autoresize = W; layer = <CALayer: 0x60000027c280>> delegate=0x101877800 standardAppearance=0x60000261cc60, when the top item belongs to a different navigation bar. topItem = <UINavigationItem: 0x100f11230> title='Overview' style=navigator, navigation bar = <PUICStackedNavigationBar: 0x100f22a80; baseClass = UINavigationBar; frame = (0 0; 198 60); opaque = NO; autoresize = W; layer = <CALayer: 0x6000002887c0>> delegate=0x101069600 standardAppearance=0x60000261f3c0, possibly from a client attempt to nest wrapped navigation controllers.'
3
1
1.2k
Sep ’23
Disabled button in SwiftUI .alert not working
I found an issue when implementing an alert with a TextField to input a name. I want the action button to be disabled until a name has been entered, but the action block is never executed when the button has become enabled and pressed. The problem seems to appear only when name is initially an empty string. Tested with iOS 17.0. struct MyView: View { @State private var name = "" var body: some View { SomeView() .alert(...) { TextField("Name", text: $name) Button("Action") { // Action }.disabled(name.isEmpty) Button("Cancel", role: .cancel) {} } } }
14
6
4.1k
Sep ’23
Window updates are broken on Sonoma
Our MacOS application has a single window which is occupied by an NSView-derived view. It's been working for the last ten years or so, but when using the Sonoma beta, window updates are badly broken. We rely on using setNeedsDisplayInRect to redisplay any portions of the view that need to be redisplayed, but no matter how small a rectangle we specify, the entire window is repainted with the background colour before our drawRect implementation is called. We already provide an overload of isOpaque in our view which returns true, and in the past this was effective for suppressing the background fill, but it no longer seems to work (although I can confirm that it is still called along the way). I've attached an image that shows an example of how a sample window looks after resizing (which is correct) and then what it looks like after using setNeedsDisplayInRect to invalidate the region occupied by the button in the centre. I've explicitly set the NSWindow background colour to blue to make it more obvious : Is it still possible to inhibit the background fill? Repainting the entire view for every update is not really an option for us, for performance reasons
6
4
2.4k
Sep ’23
No ObservableObject of type AuthViewModel found, but only on Mac
Hi. I am very new to SwiftUI and still trying to learn. I just encountered a very weird problem that I can't figure out. I have an iPad application that runs on Apple Silicon Macs as "Designed for iPad"; for some reason, this issue only comes up when running it on a Mac, even if the code is exactly the same. This is the view that's causing issues: struct ProfileEditView: View { @EnvironmentObject var mainModel: MainViewModel @EnvironmentObject var authModel: AuthViewModel [some other stuff] var body: some View { GeometryReader { geo in VStack(spacing: 20) { navigationBar() .padding(.horizontal, 3) if authModel.user != nil { VStack(alignment: .leading, spacing: 30) { PhotosPicker(selection: self.$imageSelection, matching: .images, preferredItemEncoding: .compatible) { ProfilePicView(editIconShown: true) } .disabled(authModel.profilePicIsLoading) .padding(.horizontal, geo.size.width * 0.3) .padding(.bottom) VStack(spacing: 10) { if let error = self.error { Text(error) .foregroundStyle(Color.red) .font(.footnote) .italic() } SettingsTextFieldView(String(localized: "Your name:"), value: self.$name) { if nameIsValid { authModel.updateName(self.name) } } } Spacer() actions() } .padding(.horizontal, 5) .padding(.top) .onAppear { self.name = authModel.user!.name } } } .padding() } } } Obviously, I am injecting the ViewModels instances at the app entry point: @main struct MyApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate @StateObject var authViewModel: AuthViewModel = AuthViewModel() @StateObject var mainViewModel: MainViewModel = MainViewModel() @StateObject var statsViewModel: StatsViewModel = StatsViewModel() @StateObject var purchaseViewModel: PurchaseViewModel = PurchaseViewModel() @State var revenueCatIsConfigured: Bool = false init() { // MARK: Firebase configuration FirebaseConfiguration.shared.setLoggerLevel(.min) FirebaseApp.configure() // MARK: RevenueCat configuration if let uid = AuthViewModel.getLoggedInUserID() { Purchases.logLevel = .error Purchases.configure(withAPIKey: "redacted", appUserID: uid) self.revenueCatIsConfigured = true } } var body: some Scene { WindowGroup { MainView() .environmentObject(authViewModel) .environmentObject(mainViewModel) .environmentObject(statsViewModel) .environmentObject(purchaseViewModel) } } } And lastly, ProfileEditView that is causing issues, is a subview of MainView: MainView has a switch statement, based on the selected tab; one of the possible views is SettingsView, which can show ProfileEditView as a sheet modifier. For some reason, only when running on mac, I get the error Thread 1: Fatal error: No ObservableObject of type AuthViewModel found. A View.environmentObject(_:) for AuthViewModel may be missing as an ancestor of this view. This will come up every time I reference authModel in this view alone. Both the iPad and iPhone versions work just fine, and again, the code is exactly the same, since it's a "Designed for iPad". I don't even know how to troubleshoot the issue.
5
3
1.5k
Sep ’23
SwiftUI Commands and StrictConcurrency Warnings Issue
I have enabled “StrictConcurrency” warnings in my project that uses SwiftUI. I have a Commands struct. It has a Button, whose action is calling an async method via Task{}. This builds without warnings within Views, but not Commands. There the compiler reports “Main actor-isolated property 'body' cannot be used to satisfy nonisolated protocol requirement”. Looking at SwiftUI: In View, body is declared @MainActor: @ViewBuilder @MainActor var body: Self.Body { get } In Commands, body is not declared @MainActor: @CommandsBuilder var body: Self.Body { get } So the common practice of making a Button action asynchronous: Button { Task { await model.load() } } label:{ Text("Async Button") } will succeed without warnings in Views, but not in Commands. Is this intentional? I've filed FB13212559. Thank you.
3
0
1.2k
Sep ’23
NSTextLayoutManager's enumerateTextSegments parameters documentation
This function on NSTextLayoutManager has the following signature func enumerateTextSegments( in textRange: NSTextRange, type: NSTextLayoutManager.SegmentType, options: NSTextLayoutManager.SegmentOptions = [], using block: (NSTextRange?, CGRect, CGFloat, NSTextContainer) -> Bool ) The documentation here doesn't define what the CGRect and CGFloat passed to block are. However, looking at sample code Using TextKit2 To Interact With Text, they seem to be the frame for the textsegment and baselineposition respectively. But, the textSegmentFrame seems to start at origin.x = 5.0 when text is empty. Is this some starting offset for text segments? I don't seem to be able to find mention of this anywhere.
1
0
825
Oct ’23
SF Symbol image color in the menu bar
I can set color of the SF symbol image in the application window but cannot do the same in the menu bar. I wonder how I can change the color in the menu? import SwiftUI @main struct ipmenuApp: App { var body: some Scene { MenuBarExtra { Image(systemName: "bookmark.circle.fill") .renderingMode(.original) .foregroundStyle(.red) } label: { Image(systemName: "bookmark.circle.fill") .renderingMode(.original) .foregroundStyle(.red) } } } xcodebuild -version Xcode 15.0 Build version 15A240d
4
1
1.3k
Oct ’23
Invalid Numeric Value (NaN) Error in SwiftUI's TextField on Long-Press
I'm experiencing a peculiar issue with SwiftUI's TextField. Whenever I long-press on the TextField, the console outputs an error about passing an invalid numeric value (NaN, or not-a-number) to the CoreGraphics API. This issue persists even in a new Xcode project with minimal code. Code Snippet: import SwiftUI struct ContentView: View { @State private var text: String = "" var body: some View { TextField("Placeholder", text: $text) } } 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. Steps to Reproduce: Create a new SwiftUI project in Xcode. Add a TextField to the ContentView. Run the app on a device or simulator. Long-press inside the TextField. What I've Tried: Updating to the latest version of Xcode and iOS. Using UIViewRepresentable to wrap a UIKit UITextField. Creating a new Xcode project to isolate the issue. None of these steps have resolved the issue. Questions: Has anyone else encountered this problem? Are there any known workarounds for this issue? Is this a known bug, and if so, has it been addressed in any updates?
21
33
12k
Oct ’23
iOS 17 - TextField color does not changes with state is updated
Hi! I find this code does not work as expected on iOS 17 simulator and device. It was working correctly with iOS 16: struct ContentView: View { @State private var numberText = "" var color: Color { let result = (Int(numberText) ?? 0) <= 0 if result { return .black } return .red } var body: some View { VStack { TextField("Enter a number", text: $numberText) .font(.title) .foregroundStyle( color ) Text("Font color will turn red if number > 0") .foregroundColor(.gray) } .padding() } } I tried a workaround and it works: struct ContentView: View { @State private var numberText = "" @State private var color = Color.black func updateColor() ->Color { let result = (Int(numberText) ?? 0) <= 0 if result { return .black } return .red } var body: some View { VStack { TextField("Enter a number", text: $numberText) .font(.title) .foregroundStyle( color ) .onChange(of:numberText) { color = updateColor() } Text("Font color will turn red if number > 0") .foregroundColor(.gray) } .padding() } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
6
1
1.7k
Oct ’23
Mac Catalyst: Presenting view controller <UIAlertController:> from detached view controller <MyViewController:> is not supported, and may result in incorrect safe area insets and a corrupt root presentation on Sonoma
Okay so I'm getting this log every time I present a UIAlertController: Mac Catalyst: Presenting view controller <UIAlertController: 0x10f027000> from detached view controller <MyViewController: 0x10d104080> is not supported, and may result in incorrect safe area insets and a corrupt root presentation. Make sure <MyViewController: 0x10d104080> is in the view controller hierarchy before presenting from it. Will become a hard exception in a future release. A few points: MyViewController is not detached and the presentation shows just fine. I specifically check for this before presenting the alert controller like so: BOOL okayToPresentError = (self.isViewLoaded && self.view.window != nil); if (okayToPresentError) { [self presentErrorInAlertController:error]; } else { //Wait until view did appear. self.errorToPresentInViewDidAppear = error; } It spews out every time an error is fed back to my app and I present the alert controller (I can turn off the network connection and I show an alert controller with a "retry" button in it which will loop the error back so I can replay the error alert presentation over and over again) . Every time the alert controller is presented, I get this spewing in the console. Please don't start throwing hard exceptions because the check is faulty.
3
1
2.1k
Oct ’23
SwiftUI iOS 17 White screen when I return back with Navigation Stack
When using the Navigation Stack with paths, I've faced an issue where tapping the 'back' button on the custom navigation bar results in a blank screen. With light theme the screen is white, when using dark theme the screen is black. I've found a decision with using an environment value to dismiss a single screen when needed. However, the problem becomes more prominent when I want to pop back to the root view. This issue has become since updating to iOS 17.
2
3
2.0k
Oct ’23
NavigationLinks embedded in a List getting clipped in tvOS
I want to recreate an user experience like in the settings app in tvOS. Therefore I have a HStack with some content on the left side and a List of NavigationLinks on the right side. However a focused link in the list gets clipped on the left side. I tried paddings and spacers and what not, but nothing helped. Is this is a bug or am I missing something? Here is some example code to show the problem: struct ContentView: View { var body: some View { NavigationStack { HStack(spacing: 20) { VStack(alignment: .center) { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } List { ForEach(SomeViewEnum.allCases) { someView in NavigationLink(someView.rawValue, value: someView) } } .navigationDestination(for: SomeViewEnum.self) { someView in Text(someView.rawValue) } } } } } And a screenshot to show the problem:
1
1
788
Oct ’23
New UIButton title left aligned
Hello There, I was trying to do a Button with title left aligned. With the old UIButton, I would have used the title-/contentEdgeInsets to achieve this, but with the new button these values are deprecated and do not work anymore. As far as I understood, with the new button only the spacing between the elements (sub-, title and image) is controllable. I also tried just setting the buttons width to the same width as the label, what would be possible in my case since it should be kind of a "hyperlink-button" which has no background or border. This works so far, but once the user interacts with the button, the title label gets multiline, which is on the one hand not wanted and on the other hand of course does not look left aligned anymore. (Besides the buttons height is fix in my case which leads to clipping of the title) So here again in short: Is there any way to make the title of the new UIButton left aligned inside of the button? Thank you very much in advance.
2
0
1.6k
Oct ’23
Problem with TextFields and decimals iOS17
After upgrading to iOS 17 I am struggling to get decimals working in my app - here is a sample code: for clarity I provide a complete "working" sample (I am pulling data from a back-end server using json, etc - all of that is working ok, it's the UI issue - see below): Model import Foundation struct TestFloat: Encodable { var testFloatNumber: Float = 0 } Observable Class import Foundation class TestFloatViewModel: ObservableObject { @Published var testFloat = TestFloat() } View struct TestFloatView: View { @ObservedObject var testFloatVM: TestFloatViewModel let formatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() var body: some View { VStack { HStack { Text("Enter Float Number") Spacer() } Spacer() .frame(height: 2.0) HStack { TextField("Enter Float Number", value: $testFloatVM.testFloat.testFloatNumber, formatter: formatter) .keyboardType(.decimalPad) .textFieldStyle(.roundedBorder) } } } } This is working on a device with iOS16; however when run on device with iOS17: you can enter maximum four digits? using backspace you can delete all numbers apart of the first one you cannot enter the decimal (.) at all even though decimal keyboard is provided Any help is greatly appreciated.
10
3
2.2k
Oct ’23