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

AppIntents - Choosing a default Measurement<UnitMass> for body weight based on locale
Here’s a clearer and more concise version of your question: I’m creating an AppIntent to allow users to log their body weight. My intent includes a @Parameter defined as: @Parameter( title: "Weight", description: "Current Weight", defaultUnit: .pounds, supportsNegativeNumbers: false ) var weight: Measurement<UnitMass> This works but doesn’t respect the user’s Locale and its measurementSystem. When I add defaultUnitAdjustForLocale: true to the @Parameter macro, the default always switches to kilograms, regardless of the locale. How can I correctly set the default unit to match the user’s locale for the purpose of entering a users body weight?
0
0
379
Jan ’25
Food Truck Sample animation issue from Table Component
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?
0
0
60
Apr ’25
Bidirectional Text Rendering Issue in Swift UILabel for Arabic
I'm encountering an issue displaying a large HTML string (over 11470 characters) in a UILabel. Specifically, the Arabic text within the string is rendering left-to-right instead of the correct right-to-left direction. I've provided a truncated version of the HTML string and the relevant code snippet below. I've tried setting the UILabel's text alignment to right, but this didn't resolve the issue. Could you please advise on how to resolve this bidirectional text rendering problem? The results of the correct and incorrect approaches are shown in the image below. Here's the relevant Swift code: let labelView: UILabel = { let label = UILabel() label.textAlignment = .right label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.semanticContentAttribute = .forceRightToLeft label.backgroundColor = .white label.lineBreakMode = .byWordWrapping return label }() //Important!! //It must exceed 11470 characters. let htmlString = """ &lt;p style=\"text-align: center;\"&gt;&lt;strong&gt;İSTİÂZE&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Nahl sûresindeki:&lt;/p&gt; &lt;p dir="rtl" lang="ar"&gt; فَاِذَا قَرَاْتَ الْقُرْاٰنَ فَاسْتَعِذْ بِاللّٰهِ مِنَ الشَّيْطَانِ الرَّج۪يمِ &lt;/p&gt; &lt;p&gt;&lt;strong&gt;“&lt;/strong&gt;&lt;strong&gt;Kur’an okuyacağın zaman kovulmuş şeytandan hemen Allah’a sığın!&lt;/strong&gt;&lt;strong&gt;”&lt;/strong&gt; (Nahl 16/98) emri gereğince Kur’ân-ı Kerîm okumaya başlarken:&lt;/p&gt; &lt;p dir="rtl" lang="ar"&gt;اَعُوذُ بِاللّٰهِ مِنَ الشَّيْطَانِ الرَّج۪يمِ&lt;/p&gt; &lt;p&gt;&lt;em&gt;“Kovulmuş şeytandan Allah’a sığınırım” &lt;/em&gt;deriz. Bu sözü söylemeye “istiâze&lt;em&gt;” denilir. “Eûzü”&lt;/em&gt;, sığınırım, emân dilerim, yardım taleb ederim, gibi anlamlara gelir. It must exceed 11470 characters.&lt;/p&gt; “”” if let data = htmlString.data(using: .utf8) { let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ] do { let attributedString = try NSAttributedString(data: data, options: options, documentAttributes: nil) labelView.attributedText = attributedString } catch { print("HTML string işlenirken hata oluştu: \(error)") } } I'm using iOS 18.2 and Swift 6. Any suggestions on how to correct the bidirectional text rendering?
0
0
380
Jan ’25
Reading large documents
Can the SwiftUI document architecture Take a file as read-only; never to be written out Take files too large for memory (multi-MB, or even GB) I wouldn't want the system to read a gigabyte size file into memory by default. If the system can use a memory-mapped Data as the representation, that'll be something I can make do. It would be even better if I could tell the system that I'll handle all the reading, all I need from it is a reference to the file's location on disk.
Topic: UI Frameworks SubTopic: SwiftUI
0
0
40
Apr ’25
QLPreviewingController can access previewed file, but cannot load files referenced by the previewed file
I have an app on the Mac App Store (so sandboxed) that includes a QuickLook Preview Extension that targets Markdown files. It established a QLPreviewingController instance for the macOS QuickLook system to access and it works. I'm in the process of updating it so that it displays inline images referenced in the file as well as styling the file's text. However, despite setting Downloads folder read-only access permission (and user-selected, though I know that shouldn't be required: no open/save dialogs here) in the extension's entitlements, Sandbox refuses too allow access to the test image: I always get a deny(1) file-read-data error in the log. FWIW, the test file is referenced in the source Markdown as an absolute unix file path. I've tried different signings and no joy. I’ve tried placing the referenced image in various other locations. Also no joy. All I can display is the error-case bundle image for 'missing image'. Question is, is this simply something that QuickLook extensions cannot do from within the sandbox, or am I missing something? Is there anything extra I can do to debug this?
0
0
413
Jan ’25
looking for sample code 3d wireframe (with lines ) & polygons
Looking for sample code 3d wireframe (with lines ) & polygons and should be able to rotate (set camera angles) I tried sample code seems to be complicated & getting a BLANK screen import SwiftUI import SceneKit struct SceneKitTest2: View { var body: some View { VStack{ Text("SceneKitTest2") SceneView(scene: SCNScene(named:"Earth_1_12756.scn"), options: [.autoenablesDefaultLighting,.allowsCameraControl]) .frame(width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2) Spacer(minLength: 0) } } }
0
0
399
Jan ’25
UIDocumentPickerViewController
I'm upgrading my app from minVersion iOS 11 to iOS 12. My compiler says that UIDocumentMenuViewController with UIDocumentPickerViewController is deprecated, they recommend to use directly the last one. So I change the code. fileprivate func openDocumentPicker() { let documentPicker = UIDocumentPickerViewController( documentTypes: [ "com.adobe.pdf", "org.openxmlformats.wordprocessingml.document", // DOCX "com.microsoft.word.doc" // DOC ], in: .import ) documentPicker.delegate = self view.window?.rootViewController?.present(documentPicker, animated: true, completion: nil) } When I open the picker in iOS 17.2 simulator and under it is well shown, like a page sheet. But in iOS 18.0 and up at first it opens like a page sheet with no content but then it is displayed as a transparent window with no content. Is there any issue with this component and iOS 18? If I open the picker through UIDocumentMenuViewControllerDelegate in an iphone with iOS 18.2 it is well shown. Image in iOS 18.2 with the snippet The same snippet in iOS 17.2 (and expected in older ones)
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
357
Jan ’25
Improving references to localized strings in App Intents
In order to make referencing keys for localized strings a little more reliable, our application references generated constants for localized string keys: This eliminates the potential for developers to misspell a key when referencing a localized strings. And because these constants are automatically generated by the exact same process that provides localized strings for the application, each and every constant is guaranteed to have a localized string associated with it. I’m currently attempting to implement something similar for the localized strings referenced by our new App Intents. Our initial release of App Intent functionality is simply using string literals to reference localized strings: However, I am running into several issues when trying to reference the string keys as a constant. The closest I managed to get was defining the constant as either a LocalizationValue or as a StaticString and referencing the constant while initializing the LocalizedStringResource. With this approach, I see no errors from Xcode until I try and compile. What’s more is that the wording of the error being thrown is quite peculiar: As you can see with the sample code above, I am clearly calling LocalizedStringResource’s initializer directly as Indicated by the error. Is what I’m trying to do even possible with App Intents? From my research, it does look like iOS app localization is moving more towards using string literals for localized strings. Like with String Catalog’s ability to automatically generate entries from strings referenced in UI without the need for a key. However, we’d prefer to use constants if possible for the reasons listed above.
0
0
105
Apr ’25
Activate hoverEffect on separate entity attachment view
Hi, I'm working on RealityView and I have two entities in RCP. In order to set views for both entities, I have to create two separate attachments for each entity. What I want to achieve is that when I hover (by eye) on one entity's attachment, it would trigger the hover effect of the other entity's attachment. I try to use the hoverEffectGroup, but it would only activate the hover effect in a subview, instead a complete separate view. I refer to the following WWDC instruction for the hover effect. https://developer.apple.com/videos/play/wwdc2024/10152/
0
0
68
Apr ’25
UIDocumentPickerViewController dismisses presenting view controller when selecting a file multiple times quickly
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.
0
0
121
Apr ’25
NSDocumentController subclass with remembered document options
Hi all, I am trying to allow users of my app to select extra options when opening documents, and to remember those options when re-opening documents at launch. So far best idea I have is: Subclass NSDocumentController to provide an NSOpenPanel.accessoryView with the options Create a URL bookmark for each opened file and keep a mapping of bookmarks to options On launch and when the recent documents list changes, prune the stored mappings to match only the recent items Has anyone done this before, or know of a better approach? Thank you.
Topic: UI Frameworks SubTopic: AppKit
0
0
305
Feb ’25
When presenting CPNavigationAlert the navigation bar will appear
In my CarPlay app, I am hiding the navigation bar by using the following: self.mapTemplate?.automaticallyHidesNavigationBar = true self.mapTemplate?.hidesButtonsWithNavigationBar = false I don't want the navigation bar to show unless a user interacts with the map by tapping it. Strangely, when I present a CPNavigationAlert the navigation bar will often appear and then disappear after the alert is dismissed. Is there a setting or reason that the navigation bar would be appearing when presenting this alert? I would like to keep the nav bar hidden during this time.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
71
May ’25
Implement Continuity Markup in Mac app?
Hello, is there a way to implement Continuity Markup in our own apps? (This is what I'm talking about: https://support.apple.com/en-us/102269 , scroll down to "Use Continuity Markup"). Also, why does a QuickLook panel (QLPreviewPanel.shared()) not display the markup options when triggered from my app for png image files in my app's Group Container? Do I need to implement certain NSServicesMenuRequestor methods for that? Sadly, I could not find any docs on that. Thank you, – Matthias
0
0
113
Apr ’25
Get NSTextView selection frame with NSTextLayoutManager
I'm trying to update my app to use TextKit 2. The one thing that I'm still not sure about is how I can get the selection frame. My app uses it to auto-scroll the text to keep the cursor at the same height when the text wraps onto a new line or a newline is manually inserted. Currently I'm using NSLayoutManager.layoutManager!.boundingRect(forGlyphRange:in:). The code below almost works. When editing the text or changing the selection, the current selection frame is printed out. My expectation is that the selection frame after a text or selection change should be equal to the selection frame before the next text change. I've noticed that this is not always true when the text has a NSParagraphStyle with spacing > 0. As long as I type at the end of the text, everything's fine, but if I insert some lines, then move the selection somewhere into the middle of the text and insert another newline, the frame printed after manually moving the selection is different than the frame before the newline is inserted. It seems that the offset between the two frames is exactly the same as the paragraph style's spacing. Instead when moving the selection with the arrow key the printed frames are correct. I've filed FB17104954. class ViewController: NSViewController, NSTextViewDelegate { private var textView: NSTextView! override func loadView() { let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) textView = NSTextView(frame: scrollView.frame) textView.autoresizingMask = [.width, .height] textView.delegate = self let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 40 textView.typingAttributes = [.foregroundColor: NSColor.labelColor, .paragraphStyle: paragraphStyle] scrollView.documentView = textView scrollView.hasVerticalScroller = true view = scrollView } func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool { print("before", selectionFrame.maxY, selectionFrame) return true } func textDidChange(_ notification: Notification) { print("after ", selectionFrame.maxY, selectionFrame) } func textViewDidChangeSelection(_ notification: Notification) { print("select", selectionFrame.maxY, selectionFrame) } var selectionFrame: CGRect { guard let selection = textView.textLayoutManager!.textSelections.first?.textRanges.first else { return .null } var frame = CGRect.null textView.textLayoutManager!.ensureLayout(for: selection) textView.textLayoutManager!.enumerateTextSegments(in: selection, type: .selection, options: [.rangeNotRequired]) { _, rect, _, _ in frame = rect return false } return frame } }
0
1
105
Apr ’25
Live Activity resets to initial state after 8+ hours in background
Hi Apple team and community, We’re encountering a strange issue with Live Activity that seems related to memory management or background lifecycle. ❓ Issue: Our app updates a Live Activity regularly (every 3 minutes) using .update(...). However, after the app remains in the background for around 8 hours, the Live Activity reverts to the initial state that was passed into .request(...). Even though the app continues sending updates in the background, the UI on the Lock Screen and Dynamic Island resets to the original state.
0
0
57
Apr ’25
SwiftUI views lock up after background and sleep for “Designed for iPad” apps
There's an easily reproducible SwiftUI bug on macOS where an app's UI state no longer updates/re-renders for "Designed for iPad" apps (i.e. ProcessInfo.processInfo.isiOSAppOnMac == true). The bug occurs in Xcode and also if the app is running independent of Xcode. The bug occurs when: the user Hides the app (i.e. it goes into the background) the user puts the Mac to sleep (e.g. Apple menu > Sleep) a total of ~60 seconds transpires (i.e. macOS puts the app into the "suspended state") when the app is brought back into the foreground the UI no longer updates properly The only way I have found to fix this is to manually open a new actual full app window via File > New, in which case the app works fine again in the new window. The following extremely simple code in a default Xcode project illustrates the issue: import SwiftUI @main struct staleApp: App { @State private var isBright = true var body: some Scene { WindowGroup() { ZStack { (isBright ? Color.white : Color.black).ignoresSafeArea() Button("TOGGLE") { isBright.toggle(); print("TAPPED") } } .onAppear { print("\(isBright ? "light" : "dark") view appeared") } } } } For the code above, after Hiding the app and putting the computer to sleep for 60 seconds or more, the button no longer swaps views, although the print statements still appear in the console upon tapping the button. Also, while in this buggy state, i can get the view to update to the current state (i.e. the view triggered by the last tap) by manually dragging the corner of the app window to resize the window. But after resizing, the view again does not update upon button tapping until I resize the window again. so it appears the diff engine is mucked or that the Scene or WindowGroup are no longer correctly running on the main thread I have tried rebuilding the entire view hierarchy by updating .id() on views but this approach does NOT work. I have tried many other options/hacks but have not been able to reset the 'view engine' other than opening a new window manually or by using: @Environment(.openWindow) private var openWindow openWindow could be a viable solution except there's no way to programmatically close the old window for isiOSAppOnMac (@Environment(.dismissWindow) private var dismissWindow doesn't work for iOS)
0
0
142
Apr ’25
Data Fetch issue from SensorKit
I want use SensorKit data for research purposes in my current app. I have applied for and received permission from Apple to access SensorKit Data. I have granting all the necessary permissions. But no data retrieved. I am using didCompleteFetch for retrieving data from Sensorkit. CompleteFetch method calls but find the data. Below is my SensorKitManager Code. import SensorKit import Foundation protocol SensorManagerDelegate: AnyObject { func didFetchPhoneUsageReport(_ reports: [SRPhoneUsageReport]) func didFetchAmbientLightSensorData(_ data: [SRAmbientLightSample]) func didFailFetchingData(error: Error) } class SensorManager: NSObject, SRSensorReaderDelegate { private let phoneUsageReader: SRSensorReader private let ambientLightReader: SRSensorReader weak var delegate: SensorManagerDelegate? override init() { self.phoneUsageReader = SRSensorReader(sensor: .phoneUsageReport) self.ambientLightReader = SRSensorReader(sensor: .ambientLightSensor) super.init() self.phoneUsageReader.delegate = self self.ambientLightReader.delegate = self } func requestAuthorization() { let sensors: Set<SRSensor> = [.phoneUsageReport, .ambientLightSensor] guard phoneUsageReader.authorizationStatus != .authorized || ambientLightReader.authorizationStatus != .authorized else { log("Already authorized. Fetching data directly...") fetchSensorData() return } SRSensorReader.requestAuthorization(sensors: sensors) { [weak self] error in DispatchQueue.main.async { if let error = error { self?.log("Authorization failed: \(error.localizedDescription)", isError: true) self?.delegate?.didFailFetchingData(error: error) } else { self?.log("Authorization granted.") self?.fetchSensorData() } } } } func fetchSensorData() { guard let fromDate = Calendar.current.date(byAdding: .day, value: -1, to: Date()) else { log("Failed to calculate 'from' date.", isError: true) return } let fromTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: fromDate.timeIntervalSinceReferenceDate) let toTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().timeIntervalSinceReferenceDate) let phoneUsageRequest = SRFetchRequest() phoneUsageRequest.from = fromTime phoneUsageRequest.to = toTime phoneUsageRequest.device = SRDevice.current let ambientLightRequest = SRFetchRequest() ambientLightRequest.from = fromTime ambientLightRequest.to = toTime ambientLightRequest.device = SRDevice.current phoneUsageReader.fetch(phoneUsageRequest) ambientLightReader.fetch(ambientLightRequest) } // ✅ Delegate Methods func sensorReader(_ reader: SRSensorReader, didCompleteFetch fetchRequest: SRFetchRequest) { Task.detached { if reader.sensor == .phoneUsageReport { if let samples = reader.fetch(fetchRequest) as? [SRPhoneUsageReport] { DispatchQueue.main.async { [weak self] in self?.delegate?.didFetchPhoneUsageReport(samples) } } } else if reader.sensor == .ambientLightSensor { if let samples = reader.fetch(fetchRequest) as? [SRAmbientLightSample] { DispatchQueue.main.async { [weak self] in self?.delegate?.didFetchAmbientLightSensorData(samples) } } } } } func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, didFetchResult result: SRFetchResult<AnyObject>) -> Bool { return true } func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, failedWithError error: any Error) { DispatchQueue.main.async { [weak self] in self?.delegate?.didFailFetchingData(error: error) } } // MARK: - Logging Helper private func log(_ message: String, isError: Bool = false) { if isError { print("❌ [SensorManager] \(message)") } else { print("✅ [SensorManager] \(message)") } } } And ViewController import UIKit import SensorKit class ViewController: UIViewController { private var sensorManager: SensorManager! override func viewDidLoad() { super.viewDidLoad() setupSensorManager() } private func setupSensorManager() { sensorManager = SensorManager() sensorManager.delegate = self sensorManager.requestAuthorization() } } // MARK: - SensorManagerDelegate extension ViewController: SensorManagerDelegate { func didFetchPhoneUsageReport(_ reports: [SRPhoneUsageReport]) { for report in reports { print("Total Calls: (report.totalOutgoingCalls + report.totalIncomingCalls)") print("Outgoing Calls: (report.totalOutgoingCalls)") print("Incoming Calls: (report.totalIncomingCalls)") print("Total Call Duration: (report.totalPhoneCallDuration) seconds") } } func didFetchAmbientLightSensorData(_ data: [SRAmbientLightSample]) { for sample in data { print(sample) } } func didFailFetchingData(error: Error) { print("Failed to fetch data: \(error.localizedDescription)") } } Could anyone please assist me in resolving this issue? Any guidance or troubleshooting steps would be greatly appreciated.
0
0
126
Mar ’25
Detect change to apps Screen Time Access
I'm creating an app which gamifies Screen Time reduction. I'm running into an issue with apples Screen Time setting where the user can disable my apps "Screen Time access" and get around losing the game. Is there a way to detect when this setting is disabled for my app? I've tried using AuthorizationCenter.shared.authorizationStatus but this didn't do the trick. Does anyone have an ideas?
0
0
413
Feb ’25
Trigger save of a FileDocument in a DocumentGroup?
I have a DocumentGroup working with a FileDocument, and that's fine. However, when someone creates a new document I want them to have to immediately save it. This is the behavior on ipadOS and iOS from what I can understand (you select where before the file is created). There seems to be no way to do this on macOS? I basically want to have someone: create a new document enter some basic data hit "create" which saves the file then lets the user start editing it (1), (2), and (4) are done and fairly trivial. (3) seems impossible, though...? This really only needs to support macOS but any pointers would be appreciated.
0
0
119
Apr ’25