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

Trouble using MKAnnotation on a MKMapView
Hi everyone, i'im having troubles using Annotation on a Map View. I have a a core data model called Location that conforms to NSManagedObject from CoreData and MKAnnotation form MapKit, and i'm trying to add an array of Location to a MKMview instance in a UIViewController class, by doing somethhing like this: mapView.addAnnotation(locations), but xcode compliants with a strange error which says Argument type '[Location]' does not conform to expected type 'MKAnnotation'. it's strange to me because my Location class conforms to MKAnnotation protocol and i implemented the protocol's methods (coordinate, title, subtitle). Please can anyone help me how to fix this issues. Thank you all
Topic: UI Frameworks SubTopic: UIKit Tags:
2
0
178
Mar ’25
SwiftUI revert to saved loads document multiple times
Using, the standard Apple example at https://developer.apple.com/documentation/swiftui/building-a-document-based-app-with-swiftui I only made a small change to print when reading a file, with the time. When you use 'revert to saved', it writes the current version (expected), then loads the saved version (expected), then a few seconds later (not moving the mouse, edits, etc.) it reloads the document again. Then if you click away from the window, it loads it yet again - four times! This loading of the document twice breaks apps where the loading may take longer (large documents), then the document is replaced while the user has already started editing the recently loaded document. This is a really bad bug. Any ideas? Here is the added logs: reading file! testfile.story at 2025-03-11 20:35:16 +0000 saving file! testfile.story at 2025-03-11 20:35:27 +0000 reading file! testfile.story at 2025-03-11 20:35:27 +0000 reading file! testfile.story at 2025-03-11 20:35:30 +0000 reading file! testfile.story at 2025-03-11 20:35:31 +0000 I see the same behavior with 'Revert To Last Opened'. It seems to work as expected when you browse all versions and pick a specific version.
1
0
245
Mar ’25
Error "The operation couldn't be completed. (CPSErrorDomain error 2.)" in AppClip sheet
A few days ago scanning NFC tags or QR codes for AppClips with advanced experiences started showing the error "The operation couldn't be completed. (CPSErrorDomain error 2.)" in the AppClip sheet as seen here: We are providing AppClips to our customers and they trust AppClips to always work, since it is a big part of their business. Since this is happening at our customers phones and on the phones of their customers, I don't have a sysdiagnose. I already created a feedback entry about this FB16601674. We checked everything, our AASA file, the Appstore Experiences.
8
0
648
Mar ’25
Changing the live activity without push notification
I am trying to implement "Live activity" to my app. I am following the Apple docs. Link: https://developer.apple.com/documentation/activitykit/displaying-live-data-with-live-activities Example code: struct LockScreenLiveActivityView: View { let context: ActivityViewContext<PizzaDeliveryAttributes> var body: some View { VStack { Spacer() Text("\(context.state.driverName) is on their way with your pizza!") Spacer() HStack { Spacer() Label { Text("\(context.attributes.numberOfPizzas) Pizzas") } icon: { Image(systemName: "bag") .foregroundColor(.indigo) } .font(.title2) Spacer() Label { Text(timerInterval: context.state.deliveryTimer, countsDown: true) .multilineTextAlignment(.center) .frame(width: 50) .monospacedDigit() } icon: { Image(systemName: "timer") .foregroundColor(.indigo) } .font(.title2) Spacer() } Spacer() } .activitySystemActionForegroundColor(.indigo) .activityBackgroundTint(.cyan) } } Actually, the code is pretty straightforward. We can use the timerInterval for count-down animation. But when the timer ends, I want to update the Live Activity view. If the user re-opens the app, I can update it, but what happens if the user doesn't open the app? Is there a way to update the live activity without using push notifications?
11
9
6.4k
Mar ’25
Release Build Configuration as Release Fails Preview
I have a simple SwiftUI project with two basic build configurations (Debug, Release) as shown below. I now choose Build > Scheme > Edit Scheme under Product and select Release as the current build configuration as shown below. And the Preview canvas exhibit errors. If I click on the Diagnostics button, it says under PREVIEW UPDATE ERROR OptimizationLevelError: not building -Onone ”BuildSchemeCrazyDaughter.app” needs -Onone Swift optimization level to use previews (current setting is -O) What does that mean and why don't I get the preview for the Release build configuration? Thanks.
1
0
204
Mar ’25
Question about using @Previewable
This is an issue that occurred while using SwiftUI. Cannot find '$state' in scope The other view finds properties normally. May I know why the error is occurring? The following code is the full text of the code that causes problems. import SwiftUI @Observable class HomeState { var title: String = "Home" } struct HomeView: View { @Binding var state: HomeState var body: some View { Text(state.title) } } #Preview { @Previewable @State var state: HomeState = .init() HomeView(state: $state) /// Error: Cannot find '$state' in scope } The same error occurs when using the String type rather than the object. What did I do wrong?
2
1
299
Mar ’25
Apple Cross-Platform UI Strategy
i am posting this because i seek an understanding of Apple's cross-platform UI strategy. my background is UIKit, Core Animation, and Chameleon a UIKit workalike for (then) OSX. UIKit evolved and Mac Catalyst came along. what is the positioning of Mac Catalyst? it extends and at the same time it limits AppKit. is it an AppKit extension or is it a UI framework of its own? a Mac Catalyst app is not an AppKit app, or is it? or is it sort-of? then came SwiftUI. does SwiftUI sit on top of UIKit (for iOS) and Mac Catalyst (for macOS) or is it an unrelated technology? more recently i see CoreUI messages in the debugger console. where does that fit in? will future UIKit, AppKit, Mac Catalyst, and SwiftUI all build upon CoreUI? will CoreUI become a public framework like CoreGraphics, CoreAnimation? in the old Apple docs there were block diagram overviews of how the individual frameworks would sit one on top of the other. this is what i am looking for...
Topic: UI Frameworks SubTopic: General
2
0
223
Mar ’25
SwiftUI View cannot conform custom Equatable protocol in Swift 6.
In Swift 6, stricter concurrency rules can lead to challenges when making SwiftUI views conform to Equatable. Specifically, the == operator required for Equatable must be nonisolated, which means it cannot access @MainActor-isolated properties. This creates an error when trying to compare views with such properties: Error Example: struct MyView: View, Equatable { let title: String let count: Int static func ==(lhs: MyView, rhs: MyView) -> Bool { // Accessing `title` here would trigger an error due to actor isolation. return lhs.count == rhs.count } var body: some View { Text(title) } } Error Message: Main actor-isolated operator function '==' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode. Any suggestions? Thanks FB: FB15753655 (SwiftUI View cannot conform custom Equatable protocol in Swift 6.)
6
0
1k
Mar ’25
NSTextView and TextField becomes non clickable after a alert/menu is shown
I have a NSViewController as the root view and have a switui view embedded in it via NSHostingView. override func loadView() { self.view = NSHostingView(rootView: SwiftUiView()) } } In the SwiftUiView, I have a TextField and an NSTextView embedded using NSViewRepresentable, along with a few buttons. There is also a menu: Menu { ForEach(menuItems), id: \.self) { item in Button { buttonClicked() } label: { Text(item) } } } label: { Image("DropDown") .contentShape(Rectangle()) .frame(maxWidth: .infinity) .frame(maxHeight: .infinity) } The NSTextView and TextField work fine, and I can type in them until I click on the menu or show an alert. After that, I can no longer place my cursor in the text fields. I am able to select the text but not type in it. When I click on the NSTextView or TextField, nothing happens. At first, I thought it was just a cursor visibility issue and tried typing, but I received an alert sound. I've been trying to fix this for a couple of days and haven't found any related posts. Any help would be greatly appreciated.
1
0
268
Mar ’25
Entire view re-renders when updating dictionary
I'm trying to create a form which reads and writes data to a dictionary. when I type something in a field whole form seems to update. Is there anyway to only update the field I'm typing? Android compose have something called SnapshotStateMap which allows smart re-rendering.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
120
Mar ’25
Setting launch screen image through info.plist - image stretches to cover full screen
I am developing an app in swiftUI using Xcode 12.3, deployment target iOS 14.0. The launch screen is setup through info.plist by specifying 'background color' and 'image name'. The file used in 'image name' is from Assets catalog. (PNG format, size300 x 300 and corresponding @2x and @3x resolutions) What I have observed, when the app is installed for the first time the launch image is centered and have original resolutions but all subsequent launches show launch images stretched to cover full screen. Any ideas why this is happening and how to have more consistent behavior either way? I have tried 'respect safe area' option but it does not make a difference. Thank you.
12
2
14k
Mar ’25
Crash on removal of QLPreviewController and _EXRemoteViewController
I have a controller that displays a pdf using UIDocumentInteractionController as the presented view. When users open it up, it shows fine. User gets the app backgrounded and session timed out. After timed out, when the app is brought to foreground, I bring our loginVC by removing the old VC used to show the UIDocumentInteractionController. All the crashes are happening at this point. I am not able to reproduce it, but our alert systems show we have crashes happening. The code that shows the pdf is straight forward documentViewController = UIDocumentInteractionController() documentViewController?.delegate = self documentViewController?.url = url documentViewController?.presentPreview(animated: true) and we reset it to nil in delegate documentInteractionControllerDidEndPreview Based on the crash trace, it seems like the crash happens when our login VC replaces it and only when pdf was displayed. The reason of stressing ONLY because when we have other viewcontroller present and they are removed in a similar way, we do not see any issue. So we always replace first and then add a new one childViewController.willMove(toParent: nil) childViewController.viewIfLoaded?.removeFromSuperview() childViewController.removeFromParent() addChild(childViewController) view.addSubview(childViewController.view) childViewController.view.frame = view.bounds childViewController.didMove(toParent: self) Raised a ticket with Apple, but I haven't heard back, and it's been a month. Posting here in case anyone experiences the same and has any solutions. I saw some related posts, and solution was to remove the pdf the moment the app goes to the background, but I am trying to find some alternate solution if possible.
Topic: UI Frameworks SubTopic: UIKit
0
0
223
Mar ’25
Apple Intelligence + scrolling stuck
Hey, It seems that when Apple Intelligence is enabled, scrolling can become completely broken when using an app. This is affecting several apps, including telegram: https://github.com/TelegramMessenger/Telegram-iOS/issues/1570?reload=1 It seems that UIPanGesture is affected by this. (MapKit stop being able to scroll too). Killing + Relaunching the app fix the problem. Bug report ID, containing a video: FB16780431
2
1
215
Mar ’25
business
import SwiftUI struct Product: Identifiable { let id = UUID() let name: String let pricePerKg: Double } struct ContentView: View { @State private var selectedProduct: Product? @State private var quantity: Double = 1.0 @State private var orderDate = Date() @State private var showingConfirmation = false let products = [ Product(name: "Lamb", pricePerKg: 15.0), Product(name: "Beef", pricePerKg: 20.0), Product(name: "Chicken", pricePerKg: 10.0) ] var body: some View { NavigationView { Form { Section(header: Text("Select Meat")) { Picker("Meat Type", selection: $selectedProduct) { ForEach(products) { product in Text(product.name).tag(product as Product?) } } } if let selectedProduct = selectedProduct { Section(header: Text("Quantity (kg)")) { Stepper(value: $quantity, in: 0.5...10, step: 0.5) { Text("\(quantity, specifier: "%.1f") kg") } } Section(header: Text("Delivery Date")) { DatePicker("Select Date", selection: $orderDate, in: Date()..., displayedComponents: .date) } Section(header: Text("Total Price")) { Text("$\(selectedProduct.pricePerKg * quantity, specifier: "%.2f")") } Button("Confirm Order") { showingConfirmation = true } .alert(isPresented: $showingConfirmation) { Alert(title: Text("Order Confirmed"), message: Text("You have ordered \(quantity, specifier: "%.1f") kg of \(selectedProduct.name) for \(orderDate.formatted(date: .long, time: .omitted))."), dismissButton: .default(Text("OK"))) } } } .navigationTitle("Halal Butcher") } } } @main struct HalalButcherApp: App { var body: some Scene { WindowGroup { ContentView() } } }
2
0
218
Mar ’25
Can't find or decode availabilityDetailedInfo warning when start editing textField
Whenever I start editing TextField or while editing TextField, Xcode shows this worning, and takes a few seconds to show the keyboard. There is no 'availabilityDetailedInfo' in my source code, and I could not find similar errors on the internet. Can't find or decode availabilityDetailedInfo unavailableReasonsHelper: Failed to get or decode availabilityDetailedInfo Can't find or decode reasons unavailableReasonsHelper: Failed to get or decode unavailable reasons as well Can't find or decode availabilityDetailedInfo unavailableReasonsHelper: Failed to get or decode availabilityDetailedInfo Can't find or decode reasons unavailableReasonsHelper: Failed to get or decode unavailable reasons as well
14
29
8.3k
Mar ’25
How can I use specify the anchor used to display an item that a user scrolls to ?
I have a scrollview displaying a sequence of circles, which a user should be able to scroll through to select an item. When the user stops scrolling and the animation comes to rest the circle selected should display screen-centered. I had hoped to achieve this using .scrollPosition(id: selectedItem, anchor: .center) but it appears that the anchor argument is ignored when scrolled manually. (BTW - I searched but didn't locate this aspect in the Apple documentation so I'm not confident that this observation is really correct). https://youtu.be/TpXDTuL5yPQ The video shows the user-scrolling behaviour, and also the snap-to-anchor that I would like to achieve, but I would like this WITHOUT forcing a button press. I could juggle the container size and size of the circles so that they naturally fit centered into the screen, but I would prefer a more elegant solution. How can I force the scrolling to come to rest such that the circle glides to rest in the center of the screen/container? struct ItemChooser: View { @State var selectedItem: Int? var body: some View { VStack { Text("You have picked: \(selectedItem ?? 0)") ScrollHorizontalItemChooser(selectedItem: $selectedItem) } } } #Preview { ItemChooser(selectedItem: 1) } struct ScrollHorizontalItemChooser: View { @Binding var selectedItem: Int? @State var scrollAlignment: UnitPoint? = .center let ballSize: CGFloat = 150 let items = Array(1...6) @State var scrollPosition: ScrollPosition = ScrollPosition() var body: some View { VStack { squareUpButton ScrollView(.horizontal) { HStack(spacing: 10) { showBalls } .scrollTargetLayout() } .scrollPosition(id: $selectedItem, anchor: scrollAlignment ) .overlay{ crosshairs } } } var crosshairs: some View { Image(systemName: "scope").scaleEffect(3.0).opacity(0.3) } @ViewBuilder var showBalls: some View { let screenWidth: CGFloat = UIScreen.main.bounds.width var emptySpace: CGFloat {screenWidth / 2 - ballSize / 2 - 10} Spacer(minLength: emptySpace) ForEach(items, id: \.self) { item in poolBall( item) .id(item) } Spacer(minLength: emptySpace) } @ViewBuilder private func poolBall(_ item: Int) -> some View { Text("Item \(item)") .background { Circle() .foregroundColor(Color.green) .frame(width: ballSize, height: ballSize) } .frame(width: ballSize, height: ballSize) } @ViewBuilder var squareUpButton: some View { var tempSelected: Int? = nil Button("Square up with Anchor") { tempSelected = selectedItem selectedItem = 0 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { selectedItem = tempSelected ?? 0 } } } }
Topic: UI Frameworks SubTopic: SwiftUI
1
0
244
Mar ’25
Custom SwiftUI view with localization support similar to the SwiftUI Text view
I'd like to create a custom SwiftUI view that supports extracting its title string along with the localization comment into a string catalog. Like the SwiftUI Text view does. I have a view with an init similar to the localization init of Text. But it looks like I'm missing something obvious. Two questions: How do I get the actual localized string using a LocalizedStringKey? Why is the comment not picked up and added to the string catalog? // 1) My custom view with localization support: // I'd like to build a view which supports extraction of strings into a string catalog like the SwiftUI `Text` view does. struct MyLocalizableView: View { private var localizedTitle: String init (_ titleKey: LocalizedStringKey, table: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil) { // PROBLEM I: // The following line does not work. I is a fantasy call. It depicts my idea how I would expect it to work. // My question is: How do I get the actual localized string using a `LocalizedStringKey`? self.localizedTitle = String(localizedKey: titleKey, table: table, bundle: bundle, comment: comment) } var body: some View { // At this point I want to do an operation on an actual string and not on a LocalizedStringKey. So I can't just pass the LocalizedStringKey value along. // Do `isEmpty` or some other operation on an actual string: if localizedTitle.isEmpty { Text("Show one thing") } else { Text("Show another thing") Text("** \(localizedTitle) **") } } } // 2) The call site: struct ContentView: View { var body: some View { // PROBLEM II: "My title key" is picked up and is extracted into the string catalog of the app. But the comment is NOT! MyLocalizableView("My title key", comment: "The title of the view...") .padding() } }
1
0
326
Mar ’25
Selecting TextField Causes Application Hang on Device
I'm struggling with an elusive issue, where selecting a TextField, which then shows the onscreen keyboard, causes a later application hang, but only on an actual device (not in preview, not in the simulator). I've narrowed my code down to the simplest repro. If you run the following code, you can try both the repro case and a case that avoids the issue, where the only difference between the two is whether you select a TextField, which displays the onscreen keyboard. Even if you just dismiss the keyboard, the hang still happens. To repro, select the "Press Here To Show Keyboard To Cause Hang" TextField, then select the "Press Here Before Showing Keyboard To Not Hang" link, then follow through with Create New Group, Add Member, Create New Member. The app will hang when you select Create New Member. If you start with the "Press Here Before Showing Keyboard to Not Hang", everything works. You can even select the Group Name TextField before selecting Add Member without issue. I'm looking for any ideas or suggestions, thanks. Here's the code: import SwiftUI class Member : Identifiable { let id = UUID() var name = "" } class Group : Identifiable { let id = UUID() var name = "" var members = [Member]() var memberIds = [UUID]() } struct MemberView : View { @Environment(\.dismiss) private var dismiss @Binding private var groups: [Group] @Binding private var members: [Member] @State private var member: Member init(groups: Binding<[Group]>, members: Binding<[Member]>, member: Member? = nil) { _groups = groups _members = members _member = .init(wrappedValue: member ?? Member()) } var body: some View { Form { Section(header: Text("Member Data")) { TextField("Member Name", text: $member.name) } } } } struct MembersView : View { @Environment(\.dismiss) private var dismiss @Binding private var groups: [Group] @Binding private var members: [Member] init(groups: Binding<[Group]>, members: Binding<[Member]>) { _groups = groups _members = members } var body: some View { if members.isEmpty { NavigationLink("Create New Member") { MemberView(groups: $groups, members: $members) } } else { List(members) { member in Text(member.name) } } } } struct GroupView : View { @Binding private var groups: [Group] @Binding private var members: [Member] @State private var group = Group() @State private var selectedMemberId: UUID? init(groups: Binding<[Group]>, members: Binding<[Member]>) { _groups = groups _members = members } var body: some View { Form { Section(header: Text("Group Data")) { TextField("Group Name", text: $group.name) } Section(header: Text("Members")) { List(members) { member in if group.memberIds.contains(member.id) { NavigationLink { MemberView(groups: $groups, members: $members, member: member) } label: { Text(member.name) } } } NavigationLink { MembersView(groups: $groups, members: $members) } label: { Text("Add Member") } } } } } struct GroupsView : View { @Binding private var groups: [Group] @Binding private var members: [Member] init(groups: Binding<[Group]>, members: Binding<[Member]>) { _groups = groups _members = members } var body: some View { if groups.isEmpty { NavigationLink("Create New Group") { GroupView(groups: $groups, members: $members) } } else { List(groups) { group in Text(group.name) } } } } struct MainView : View { @State private var groups: [Group] @State private var members: [Member] @State private var settings: [String] @State private var setting = "" init() { _groups = .init(wrappedValue: []) _members = .init(wrappedValue: []) _settings = .init(wrappedValue: []) } var body: some View { NavigationStack { if settings.isEmpty { VStack { TextField("Press Here To Show Keyboard To Cause Hang (Whether Or Not You Type Anything)", text: $setting) { settings.append("Hang") } Button("Press Here Before Showing Keyboard To Not Hang") { settings.append("No Hang") } } } else { GroupsView(groups: $groups, members: $members) } } } } #Preview { MainView() } @main struct TestApp: App { var body: some Scene { WindowGroup { MainView() } } }
Topic: UI Frameworks SubTopic: SwiftUI
3
0
390
Mar ’25