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

Custom keypad touchUpInside events not working in iOS18
I have a custom keypad to accept numeric input for iPads that I have been using for many years now. This is longstanding working code. With iOS 18 the touchUpInside (and other) events in the underlying Objective-C modules are not called in the file owner module when activated from the interface. The buttons seem to be properly activated based on the visual cues (they change colors when pressed). This is occurring in both simulators and on hardware. Setting the target OS version does not help. What could the cause and/or solution of this be?
0
0
67
Mar ’25
iPadOS 18 App (on Apple Silicon) - Duplicate Tab Bar Appearing in Toolbar
With iPadOS 18, the UITabBar now defaults to the floating style. I successfully reverted the tab bar to its traditional style by overriding the UITabBarController's horizontalSizeClass property: self.tabBarController?.traitOverrides.horizontalSizeClass = .unspecified When I launch the app on my Mac using Apple Silicon, TWO tab bars appear: One appears at the bottom of the screen, like a traditional tab bar. The second tab bar is still embedded in the app toolbar in its floating style. Is this a bug? How do you ensure that overriding the horizontalSizeClass will remove/hide the floating tab bar when running an app on Apple Silicon? TIA! (Demonstrated on a test project)
0
0
484
Jan ’25
How to Visualize Data in a DataFrame Using Charts
I want to visualize the data stored in a DataFrame using various charts (barmark, sectormark, linemark, etc.). My questions are as follows: Can a DataFrame be used directly within a chart? If so, could you provide a simple example? If it cannot be used directly, what is the correct way to use it? Could you provide an example? Thank you for your help. Best regards.
0
1
388
Jan ’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
173
Mar ’25
SwiftUI image has isAccessibilityElement == false
My SwiftUI app uses an Image with a tap gesture: Image(systemName: "xmark.circle.fill") .accessibilityIdentifier(kTextFieldClearButton) .foregroundColor(.secondary) .padding(.trailing, 6) .onTapGesture { dataSource.textFieldText = "" } In a UI test, I want to tap this image to execute its action: let clearButton = app.images[kTextFieldClearButton] clearButton.tap() However the action is not executed. I then set a breakpoint at clearButton.tap(), to execute lldb commands. Here are the results: (lldb) p clearButton.isHittable t = 439.54s Find the "TextFieldClearButton" Imag (Bool) true e It is a little strange that "Image" has been interrupted by (Bool) true, but the image is hittable. p clearButton.isAccessibilityElement gives (lldb) p clearButton.isAccessibilityElement (Bool) false I don't understand why this Image is no accessibility element. I thought, SwiftUI Views are by default accessible. What can I do to make it accessible so that clearButton.tap() works as expected?
0
0
511
Dec ’24
How to replace default user location annotation with custom avatar in SwiftUI Map with selection parameter?
I'm implementing a Map with user location customization in SwiftUI using iOS 17+ MapKit APIs. When using the selection parameter with Map, the default blue dot user location becomes tappable but shows an empty annotation view. However, using UserAnnotation makes the location marker non-interactive. My code structure: import SwiftUI import MapKit struct UserAnnotationSample: View { @State private var position: MapCameraPosition = .userLocation(fallback: .automatic) @State private var selectedItem: MapSelection<MKMapItem>? var body: some View { Map(position: $position, selection: $selectedItem) { // UserAnnotation() } .mapControls { MapUserLocationButton() } } } Key questions: How can I replace the empty annotation view with a custom avatar when tapping the user location? Is there a way to make UserAnnotation interactive with selection? Should I use tag modifier for custom annotations? What's the proper way to associate selections?
0
0
309
Mar ’25
Keyboard Inaccessibility after Password Save Prompt and App Backgrounding
Hi everyone, I've come across an issue on iOS that seems to affect many apps. Here's what happens: A user logs in with correct credentials and proceeds to the OTP verification screen as part of multi factor authentication. iOS presents the system password save prompt ("Would you like to save this password?"). Without selecting an option on this prompt, the user backgrounds the app (e.g., to check their email for the OTP). Upon returning to the app, the keyboard becomes completely inaccessible on the OTP screen or any other screen. From my testing, this behavior appears to be an OS-level bug, as it occurs consistently across various apps. Has anyone else encountered this? Any known workarounds or updates from Apple on this behavior would be greatly appreciated! Thanks!
Topic: UI Frameworks SubTopic: UIKit
0
4
307
Jan ’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
227
Mar ’25
How to override NSWindow in a pure SwiftUI Application
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?
0
0
280
Mar ’25
Button Behavior between fullScreenCover and sheet
The behavior of the Button in ScrollView differs depending on how the View is displayed modally. When the View is displayed as a .fullScreenCover, if the button is touched and scrolled without releasing the finger, the touch event is canceled and the action of the Button is not called. On the other hand, if the View is displayed as a .sheet, the touch event is not canceled even if the view is scrolled without lifting the finger, and the action is called when the finger is released. In order to prevent accidental interaction, I feel that the behavior of .fullScreenCover is better, as it cancels the event immediately when scrolling. Can I change the behavior of .sheet? Demo movie is here: https://x.com/kenmaz/status/1896498312737611891 Sample code import SwiftUI @main struct SampleApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State private var showSheet = false @State private var showFullScreen = false var body: some View { VStack(spacing: 16) { Button("Sheet") { showSheet.toggle() } Button("Full screen") { showFullScreen.toggle() } } .sheet(isPresented: $showSheet) { SecondView() } .fullScreenCover(isPresented: $showFullScreen) { SecondView() } .font(.title) } } struct SecondView: View { @Environment(\.dismiss) var dismiss var body: some View { ScrollView { Button("Dismiss") { dismiss() } .buttonStyle(MyButtonStyle()) .padding(.top, 128) .font(.title) } } } private struct MyButtonStyle: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration .label .foregroundStyle(.red) .background(configuration.isPressed ? .gray : .clear) } }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
186
Mar ’25
SwiftUI Gestures prevent subview gesture when build with XCode 16 in iOS 18
I have a view with some buttons, and add 2 gestures using simultaneously. My app works well when built with XCode less than 16, or run on iOS less than 18.0. Example code is below: VStack(spacing: 0) { Button { print("button tapped") } label: { Rectangle() .foregroundColor(.red) } .frame(height: 100) } .gesture( DragGesture(minimumDistance: 0) .onEnded { value in print("single tap") } .simultaneously(with: TapGesture(count: 2).onEnded { print("double tap") } ) ) .frame(width: 200, height: 200) .border(Color.purple) I expect the action on Button should be recognized and print out button tapped, but only single tap and double tap are recognized
0
1
339
Mar ’25
Occasional PDFKit crash at PageLayout::getWordRange(unsigned long, long)
At this line of code (SketchTextSelectionManager.swift:449), sometimes there will be crashes based on crashlytics reports. let selection = pdfPage.selectionForWord(at: location) This is directly calling into PDFKit's PDFPage#selection method: https://developer.apple.com/documentation/pdfkit/pdfpage/selectionforword(at:) Attached the full stacktrace: Crashed: com.apple.root.user-initiated-qos.cooperative 0 CoreGraphics 0x30c968 PageLayout::getWordRange(unsigned long, long) const + 908 1 CoreGraphics 0x30bbc0 PageLayout::getTextRangeIndex(CGPoint, CGPDFSelectionType, SelectionPrecision) const + 2292 2 CoreGraphics 0x44a53c CGPDFSelectionCreateBetweenPointsWithOptions + 384 3 PDFKit 0x8d5f8 -[PDFPage selectionFromPoint:toPoint:type:] + 168 4 PDFKit 0x92040 -[PDFPage _rvItemAtPoint:] + 64 5 PDFKit 0x91f4c -[PDFPage rvItemAtPoint:] + 84 6 PDFKit 0x8caa8 -[PDFPage selectionForWordAtPoint:] + 40 7 MyApp 0x8420e0 closure #1 in SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 449 (SketchTextSelectionManager.swift:449) 8 MyApp 0x841a70 SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 205 (CurrentNoteManager.swift:205) 9 libswift_Concurrency.dylib 0x61104 swift::runJobInEstablishedExecutorContext(swift::Job*) + 252 10 libswift_Concurrency.dylib 0x63a28 (anonymous namespace)::ProcessOutOfLineJob::process(swift::Job*) + 480 11 libswift_Concurrency.dylib 0x611c4 swift::runJobInEstablishedExecutorContext(swift::Job*) + 444 12 libswift_Concurrency.dylib 0x62514 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 144 13 libdispatch.dylib 0x15d8c _dispatch_root_queue_drain + 392 14 libdispatch.dylib 0x16590 _dispatch_worker_thread2 + 156 15 libsystem_pthread.dylib 0x4c40 _pthread_wqthread + 228 16 libsystem_pthread.dylib 0x1488 start_wqthread + 8 ```
0
1
297
Feb ’25
Putting buttons over SwiftUI map view
Has anyone gotten custom buttons to work on top of tvOS Map()? I've tried many variations of FocusState focusSection .defaultFocus() and as soon as the map appears at startup the buttons never get focus again. They are on a ZStack over the map. I could post code but truthfully nothing works for me. I'm wondering if anyone has successfully put focusable buttons on top of the map view.
0
0
225
Mar ’25
LazyHstack in SwiftUI not supporting varying height views
In SwiftUI I want to create a list with LazyVstack and each row item in the LazyVstack is a LazyHstack of horizontally scrollable list of images with some description with line limit of 3 and width of every item is fixed to 100 but height of every item is variable as per description text content. But in any of the rows if the first item has image description of 1 line and the remaining items in the same row has image description of 3 lines then the LazyHStack is truncating all the image descriptions in the same row to one line making all the items in that row of same height. Why LazyHStack is not supporting items of varying height ? Expected behaviour should be that height of every LazyHStack should automatically adjust as per item content height. But it seems SwiftUI is not supporting LazyHstack with items of varying height. Will SwiftUI ever support this feature?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
260
Feb ’25
SwiftUI @Observable Causes Extra Initializations When Using Reference Type Properties
I've encountered an issue where using @Observable in SwiftUI causes extra initializations and deinitializations when a reference type is included as a property inside a struct. Specifically, when I include a reference type (a simple class Empty {}) inside a struct (Test), DetailsViewModel is initialized and deinitialized twice instead of once. If I remove the reference type, the behavior is correct. This issue does not occur when using @StateObject instead of @Observable. Additionally, I've submitted a feedback report: FB16631081. Steps to Reproduce Run the provided SwiftUI sample code (tested on iOS 18.2 & iOS 18.3 using Xcode 16.2). Observe the console logs when navigating to DetailsView. Comment out var empty = Empty() in the Test struct. Run again and compare console logs. Change @Observable in DetailsViewModel to @StateObject and observe that the issue no longer occurs. Expected Behavior The DetailsViewModel should initialize once and deinitialize once, regardless of whether Test contains a reference type. Actual Behavior With var empty = Empty() present, DetailsViewModel initializes and deinitializes twice. However, if the reference type is removed, or when using @StateObject, the behavior is correct (one initialization, one deinitialization). Code Sample import SwiftUI enum Route { case details } @MainActor @Observable final class NavigationManager { var path = NavigationPath() } struct ContentView: View { @State private var navigationManager = NavigationManager() var body: some View { NavigationStack(path: $navigationManager.path) { HomeView() .environment(navigationManager) } } } final class Empty { } struct Test { var empty = Empty() // Comment this out to make it work } struct HomeView: View { private let test = Test() @Environment(NavigationManager.self) private var navigationManager var body: some View { Form { Button("Go To Details View") { navigationManager.path.append(Route.details) } } .navigationTitle("Home View") .navigationDestination(for: Route.self) { route in switch route { case .details: DetailsView() .environment(navigationManager) } } } } @MainActor @Observable final class DetailsViewModel { var fullScreenItem: Item? init() { print("DetailsViewModel Init") } deinit { print("DetailsViewModel Deinit") } } struct Item: Identifiable { let id = UUID() let value: Int } struct DetailsView: View { @State private var viewModel = DetailsViewModel() @Environment(NavigationManager.self) private var navigationManager var body: some View { ZStack { Color.green Button("Show Full Screen Cover") { viewModel.fullScreenItem = .init(value: 4) } } .navigationTitle("Details View") .fullScreenCover(item: $viewModel.fullScreenItem) { item in NavigationStack { FullScreenView(item: item) .navigationTitle("Full Screen Item: \(item.value)") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { withAnimation(completionCriteria: .logicallyComplete) { viewModel.fullScreenItem = nil } completion: { var transaction = Transaction() transaction.disablesAnimations = true withTransaction(transaction) { navigationManager.path.removeLast() } } } } } } } } } struct FullScreenView: View { @Environment(\.dismiss) var dismiss let item: Item var body: some View { ZStack { Color.red Text("Full Screen View \(item.value)") .navigationTitle("Full Screen View") } } } Console Output With var empty = Empty() in Test DetailsViewModel Init DetailsViewModel Init DetailsViewModel Deinit DetailsViewModel Deinit Without var empty = Empty() in Test DetailsViewModel Init DetailsViewModel Deinit Using @StateObject Instead of @Observable DetailsViewModel Init DetailsViewModel Deinit Additional Notes This issue occurs only when using @Observable. Switching to @StateObject prevents it. This behavior suggests a possible issue with how SwiftUI handles reference-type properties inside structs when using @Observable. Using a struct-only approach (removing Empty class) avoids the issue, but that’s not always a practical solution. Questions for Discussion Is this expected behavior with @Observable? Could this be an unintended side effect of SwiftUI’s state management? Are there any recommended workarounds apart from switching to @StateObject? Would love to hear if anyone else has run into this or if Apple has provided any guidance!
0
0
328
Feb ’25
CATransaction commit() crashed on background thread [EXC_BREAKPOINT: com.apple.root.****-qos.cooperative]
Problem Description We are developing a app for iOS and iPadOS that involves extensive custom drawing of paths, shapes, texts, etc. To improve drawing and rendering speed, we use CARenderer to generate cached images (CGImage) on a background thread. We adopted this approach based on this StackOverflow post: https://stackoverflow.com/a/75497329/9202699. However, we are experiencing frequent crashes in our production environment that we can hardly reproduce in our development environment. Despite months of debugging and seeking support from DTS and the Apple Feedback platform, we have not been able to fully resolve this issue. Our recent crash reports indicate that the crashes occur when calling CATransaction.commit(). We suspect that CATransaction may not be functioning properly outside the main thread. However, based on feedback from the Apple Feedback platform, we were advised to use CATransaction.begin() and CATransaction.commit() on a background thread. If anyone has any insights, we would greatly appreciate it. Code Sample The line CATransaction.commit() is causing the crash: [EXC_BREAKPOINT: com.apple.root.****-qos.cooperative] private let transactionLock = NSLock() // to ensure one transaction at a time private let device = MTLCreateSystemDefaultDevice()! @inline(never) static func drawOnCGImageWithCARenderer( layerRect: CGRect, itemsToDraw: [ItemsToDraw] ) -> CGImage? { // We have encapsulated everything related to CALayer and its // associated creations and manipulations within CATransaction // as suggested by engineers from Apple Feedback Portal. transactionLock.lock() CATransaction.begin() // Create the root layer. let layer = CALayer() layer.bounds = layerRect layer.masksToBounds = true // Add one sublayer for each item to draw itemsToDraw.forEach { item in // We have thousands or hundred thousands of drawing items to add. // Each drawing item may produce a CALayer, CAShapeLayer or CATextLayer. // This is also why we want to utilise CARenderer to leverage GPU rendering. layer.addSublayer( item.createCALayerOrCATextLayerOrCAShapeLayer() ) } // Create MTLTexture and CARenderer. let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor( pixelFormat: .rgba8Unorm, width: Int(layer.frame.size.width), height: Int(layer.frame.size.height), mipmapped: false ) textureDescriptor.usage = [MTLTextureUsage.shaderRead, .shaderWrite, .renderTarget] let texture = device.makeTexture(descriptor: textureDescriptor)! let renderer = CARenderer(mtlTexture: texture) renderer.bounds = layer.frame renderer.layer = layer.self /* ********************************************************* */ // From our crash report, this is where the crash happens. CATransaction.commit() /* ********************************************************* */ transactionLock.unlock() // Rendering layers onto MTLTexture using CARenderer. renderer.beginFrame(atTime: 0, timeStamp: nil) renderer.render() renderer.endFrame() // Draw MTLTexture onto image. guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), let ciImage = CIImage(mtlTexture: texture, options: [.colorSpace: colorSpace]) else { return nil } // Convert CIImage to CGImage. let context = CIContext() return context.createCGImage(ciImage, from: ciImage.extent) }
0
1
469
Jan ’25