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

Post

Replies

Boosts

Views

Activity

swift DeviceActivityReport run in background
DeviceActivityReport presents statistics for a device: https://developer.apple.com/documentation/deviceactivity/deviceactivityreport The problem: DeviceActivityReport can present statistics with a delay for a parent device (when DeviceActivityReport is presenting, the DeviceActivityReportExtension is called to process the statistics). One possible solution is to call DeviceActivityReport periodically throughout the day in a child device. However, the app will not be available all day. Is there any way to run DeviceActivityReport in the background? I have tried the following approach, but it didn’t work (DeviceActivityReportExtension didnt call): let hostingController: UIHostingController? = .init(rootView: DeviceActivityReport(context, filter: filter)) hostingController?.view.frame = .init(origin: .zero, size: .init(width: 100, height: 100)) hostingController?.beginAppearanceTransition(true, animated: false) hostingController?.loadView() hostingController?.viewDidLoad() try? await Task.sleep(for: .seconds(0.5)) hostingController?.viewWillAppear(true) hostingController?.viewWillLayoutSubviews() try? await Task.sleep(for: .seconds(0.5)) hostingController?.viewDidAppear(true) try? await Task.sleep(for: .seconds(0.5)) hostingController?.didMove(toParent: rootVC) try? await Task.sleep(for: .seconds(0.5)) hostingController?.viewWillLayoutSubviews() hostingController?.viewDidLayoutSubviews() hostingController?.view.layoutIfNeeded() hostingController?.view.layoutSubviews() hostingController?.endAppearanceTransition() Is there any way to run DeviceActivityReport in the background? (when app is not visible/closed). The main problem is call DeviceActivityReport
0
0
26
2h
SF symbol effects don't work unless font modifier is applied
why do I need to set the font of an image of an SF symbol to get the effect to work? This should be a bug, it's bad behavior. Xcode 16.1 iOS 18.1, so frustrating. for example: this works Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90.circle.fill") .symbolEffect(.rotate, options: .repeat(.continuous), value: isActive) .font(.largeTitle) .onAppear() { isActive = true } but this does not animate, which makes no sense Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90.circle.fill") .symbolEffect(.rotate, options: .repeat(.continuous), value: isActive) .onAppear() { isActive = true } its the same if you use a simple setup and different font size, and whether font is before or after the symbol effect Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90.circle.fill") .font(.headline) // only works if this line is here .symbolEffect(.rotate, options: .repeat(.continuous))
0
0
26
3h
StoreKit Causing Unrelated SwiftUI View to Freeze
Hello everyone! I've encountered an issue related to SwiftUI and StoreKit. Please take a look at the SwiftUI code snippet below: import SwiftUI struct ContentView: View { var body: some View { NavigationStack { List { NavigationLink { Page1() } label: { Text("Go to Page 1") } } } } } struct Page1: View { @Environment(\.dismiss) private var dismiss @State private var string: String = "" var body: some View { List { NavigationLink { List { Page2(string: $string) .simpleValue(4) } } label: { Text("Tap this button will freeze the app") } } .navigationTitle("Page 1") } } struct Page2: View { @Binding var string: String? init(string: Binding<String>) { self._string = Binding(string) } var body: some View { Text("Page 2") } } extension EnvironmentValues { @Entry var simpleValue: Int = 3 } extension View { func simpleValue(_ value: Int) -> some View { self.environment(\.simpleValue, value) } } This view runs normally until the following symbol is referenced anywhere in the project: import StoreKit extension View { func notEvenUsed() -> some View { self.manageSubscriptionsSheet(isPresented: .constant(false)) } } It seems that once the project links the View.manageSubscriptionsSheet(isPresented:) method, regardless of whether it's actually used, it causes the above SwiftUI view to freeze. Steps to Reproduce: Clone the repository: https://github.com/gongzhang/StrangeFreeze Open it in Xcode 16 and run on iOS 17-18.1 Navigate to the second page and tap the button, causing the app to freeze. Remove manageSubscriptionsSheet(...), then everything will work fine
1
0
32
4h
shouldAutomaticallyForwardAppearanceMethods returns NO by default in UITabBarController, but documentation states YES
Hi all, I’ve been facing a behavior issue with shouldAutomaticallyForwardAppearanceMethods in UITabBarController. According to Apple’s documentation, this property should default to YES, which means that the appearance lifecycle methods (like viewWillAppear and viewDidAppear) should be automatically forwarded to child view controllers. However, in my current development environment, I’ve noticed that shouldAutomaticallyForwardAppearanceMethods returns NO by default in UITabBarController, and this is causing some issues with lifecycle management in my app. I even tested this behavior in several projects, both in Swift and Objective-C, and the result is consistent. Here are some details about my setup: I’m using Xcode 16.0 with iOS 16.4 Simulator. I’ve tested the behavior in both a new UIKit project and a simple SwiftUI project that uses a UITabBarController. Even with a clean new project, the value of shouldAutomaticallyForwardAppearanceMethods is NO by default. This behavior contradicts the official documentation, which states that it should be YES by default. Could someone clarify if this is expected behavior in newer versions of iOS or if there is a known issue regarding this? Any help or clarification would be greatly appreciated! Thanks in advance!
1
0
69
13h
UIViewRepresentable & MVVM
I am trying to get my head around how to implement a MapKit view using UIViewRepresentable (I want the map to rotate to align with heading, which Map() can't handle yet to my knowledge). I am also playing with making my LocationManager an Actor and setting up a listener. But when combined with UIViewRepresentable this seems to create a rather convoluted data flow since the @State var of the vm needs to then be passed and bound in the UIViewRepresentable. And the listener having this for await location in await lm.$lastLocation.values seems at least like a code smell. That double await just feels wrong. But I am also new to Swift so perhaps what I have here actually is a good approach? struct MapScreen: View { @State private var vm = ViewModel() var body: some View { VStack { MapView(vm: $vm) } .task { vm.startWalk() } } } extension MapScreen { @Observable final class ViewModel { private var lm = LocationManager() private var listenerTask: Task&lt;Void, Never&gt;? var course: Double = 0.0 var location: CLLocation? func startWalk() { Task { await lm.startLocationUpdates() } listenerTask = Task { for await location in await lm.$lastLocation.values { await MainActor.run { if let location { withAnimation { self.location = location self.course = location.course } } } } } Logger.map.info("started Walk") } } struct MapView: UIViewRepresentable { @Binding var vm: ViewModel func makeCoordinator() -&gt; Coordinator { Coordinator(parent: self) } func makeUIView(context: Context) -&gt; MKMapView { let view = MKMapView() view.delegate = context.coordinator view.preferredConfiguration = MKHybridMapConfiguration() return view } func updateUIView(_ view: MKMapView, context: Context) { context.coordinator.parent = self if let coordinate = vm.location?.coordinate { if view.centerCoordinate != coordinate { view.centerCoordinate = coordinate } } } } class Coordinator: NSObject, MKMapViewDelegate { var parent: MapView init(parent: MapView) { self.parent = parent } } } actor LocationManager{ private let clManager = CLLocationManager() private(set) var isAuthorized: Bool = false private var backgroundActivity: CLBackgroundActivitySession? private var updateTask: Task&lt;Void, Never&gt;? @Published var lastLocation: CLLocation? func startLocationUpdates() { updateTask = Task { do { backgroundActivity = CLBackgroundActivitySession() let updates = CLLocationUpdate.liveUpdates() for try await update in updates { if let location = update.location { lastLocation = location } } } catch { Logger.location.error("\(error.localizedDescription)") } } } func stopLocationUpdates() { updateTask?.cancel() updateTask = nil } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { switch clManager.authorizationStatus { case .authorizedAlways, .authorizedWhenInUse: isAuthorized = true // clManager.requestLocation() // ?? case .notDetermined: isAuthorized = false clManager.requestWhenInUseAuthorization() case .denied: isAuthorized = false Logger.location.error("Access Denied") case .restricted: Logger.location.error("Access Restricted") @unknown default: let statusString = clManager.authorizationStatus.rawValue Logger.location.warning("Unknown Access status not handled: \(statusString)") } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { Logger.location.error("\(error.localizedDescription)") } }
1
0
69
1d
Swift Charts: chartScrollTargetBehavior fails to snap to a day unit
I am working on a scrollable chart that displays days on the horizontal axis. As the user scrolls, I always want them to be able to snap to a specific day. I implemented the following steps described in this WWDC23 session to achieve this. I have set the chartScrollTargetBehavior to .valueAligned(matching: DateComponents(hour: 0)) I have set the x value unit on the BarMark to Calendar.Component.day I ended up with the chart code that looks like this: Chart(dates, id: \.self) { date in BarMark( x: .value("Date", date, unit: Calendar.Component.day), y: .value("Number", 1) ) .annotation { Text(date.formatted(.dateTime.day())) .font(.caption2) } } .chartXAxis { AxisMarks(format: .dateTime.day()) } .chartScrollableAxes(.horizontal) .chartScrollTargetBehavior(.valueAligned(matching: DateComponents(hour: 0))) .chartXVisibleDomain(length: fifteenDays) .chartScrollPosition(x: $selection) However, this fails to work reliably. There is often a situation where the chart scroll position lands on, for instance, Oct 20, 11:56 PM, but the chart snaps to Oct 21. I attempted to solve this problem by introducing an intermediate binding between a state value and a chart selection. This binding aims to normalize the selection always to be the first moment of any given date. But this hasn't been successful. private var selectionBinding: Binding<Date> { Binding { Calendar.current.startOfDay(for: selection) } set: { newValue in self.selection = Calendar.current.startOfDay(for: newValue) } } It's also worth mentioning that this issue also exists in Apple's sample project on Swift Charts. How would you approach solving this? How can I find a way to make the chart scroll position blind to time values and only recognize whole days? Here's the minimal reproducible example project for your reference.
1
0
85
1w
Textfield producing : Can't find or decode reasons, Failed to get or decode unavailable reasons
How to reproduce: create blank Xcode project run on physical iPhone(mine 14 pro) not simulator, updated iOS18.1.1 most up to date, on Xcode 16.1 make a text field enter any value in it in console: Can't find or decode reasons Failed to get or decode unavailable reasons This is happening in my other projects as well and I don't know a fix for it is this just an Xcode bug random log noise? It makes clicking the text field lag sometimes on initial tap.
0
0
73
14h
Changing the font size of a row - view-base tableview
So I'm following this code here where I'm using a tableview to display the files contained in a folder along with a group cell to display the name of the current folder: Here's my tableView:isGroupRow method: method which basically turns every row with the folder name into a group row (which is displayed in red in the previous image ). -(BOOL)tableView:(NSTableView *)tableView isGroupRow:(NSInteger)row { DesktopEntity *entity = _tableContents[row]; if ([entity isKindOfClass:[DesktopFolderEntity class]]) { return YES; } return NO; } and here's my tableView:viewForTableColumn:row: method where I have two if statements to decide whether the current row is a group row (meaning it's a folder) or an image: -(NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row; { DesktopEntity *entity = _tableContents[row]; if ([entity isKindOfClass:[DesktopFolderEntity class]]) { NSTextField *groupCell = [tableView makeViewWithIdentifier:@"GroupCell" owner:self]; [groupCell setStringValue: entity.name]; [groupCell setFont:[NSFont fontWithName:@"Arial" size:40]]; [groupCell setTextColor:[NSColor magentaColor]]; return groupCell; } else if ([entity isKindOfClass:[DesktopImageEntity class]]) { NSTableCellView *cellView = [tableView makeViewWithIdentifier:@"ImageCell" owner:self]; [cellView.textField setStringValue: entity.name]; [cellView.textField setFont:[NSFont fontWithName:@"Impact" size:20]]; [cellView.imageView setImage: [(DesktopImageEntity *)entity image]]; return cellView; } return nil; } Now, if the current row is an image, I change its font to Impact with a size of 40 and that works perfectly, the problem here is with the first IF statement, for a group row I wanted to change the font size to arial with a size of 40 with a magenta color but for some reason I can only get the color to work: You can see that my changes to the font size didn't work here, what gives? How can I change the font size for the group row ?
0
0
49
14h
App that runs fine under Xcode 15 does not work on Xcode 16.
When I upgraded to Sequoia 15.1, an app that worked fine under OS 14 stopped working. Out of 4 views on the main screen, only 1 is visible. Yet, if I click where another view should be, I get the expected action so the views are there, just not visible. Only I can't see where I am clicking! I had to upgrade to Xcode 16 to recompile the app and run it in Debug mode. When I do, I get the following: NSBundle file:///System/Library/PrivateFrameworks/MetalTools.framework/ principal class is nil because all fallbacks have failed. Can't find or decode disabled use cases. applicationSupportsSecureRestorableState FWIW - the only view that actually shows up is the last subview added to the main view.
2
1
229
2w
App behavior changed under Sequoia 15.1.
I have an old Objective-C app that has been running for several years. The last compilation was in February 2024. I just upgraded to Sequoia 15.1. The app has four subviews on its main view. When I run the app only the subview that was the last one instantiated is visible. I know the other subviews are there, because a random mouse click in one invisible view causes the expected change in the visible view. What changed in 15.1 to cause this?
4
0
198
1w
Horizontal window/map on visionOS
Hi, would anyone be so kind and try to guide me, which technologies, Kits, APIs, approaches etc. are useful for creating a horizontal window with map (preferrably MapKit) on visionOS using SwiftUI? I was hoping to achieve scenario: User can walk around and interact with horizontal map window and also interact with (3D) pins on the map. Similar thing was done by SAP in their "SAP Analytics Cloud" app (second image from top). Since I am complete beginner in this area, I was looking for a clean, simple solution. I need to know, if AR/RealityKit is necessary or is this achievable only using native SwiftUI? I tried using just Map() with .rotation3DEffect() which actually makes the map horizontal, but gestures on the map are out of sync and I really dont know, if this approach is valid or complete rubbish. Any feedback appreciated.
1
0
74
2d
SwiftUI Color Issue
I have ran into an issue that is illustrated by the code in the following GitHub repository. https://github.com/dougholland/ColorTest When a SwiftUI color originates from the ColorPicker it can be persisted correctly and renders the same as the original color. When the color originates from the MapFeature.backgroundColor, it is always rendered with the light appearance version of the color and not the dark appearance version. The readme in the GitHub repo has screenshots that show this. Any assistance would be greatly appreciated as this is affecting an app that is in development and I'd like to resolve this before the app is released. If this is caused by a framework bug, any possible workaround would be greatly appreciated also. I suspect it maybe a framework issue, possibly with some code related to the MapFeature.backgroundColor, because the issue does not occur when the color originates from the ColorPicker.
1
1
130
6d
Live Acitivities - ProgressView problem
Hello i ve implemented progressview and updating the state via push notification. the progress view wants closedrange which i followed but whenever i get update, the progress value resets to beginning my range is like : Date.now..endDate but i dont get it, lets assume that i get the date from database and initialized already then how the code will understand that what progress value will be as current ? it has to be something like i suppose : startDate..Date.now..endDate thanks
0
0
79
1d
Issue with .itemProvider on macOS 15.1
I have a List with draggable items. According to this thread (https://developer.apple.com/forums/thread/664469) I had to use .itemProvider instead of .onDrag, because otherwise the selection of the list will not work anymore. The items in my list refer to a file URL. So the dragging allowed to copy the files to the destination of the drag & drop. Therefore I used this code .itemProvider { let url = ....... // get the url with an internal function return NSItemProvider(object: url as NSURL) } Since the update to macOS 15.1 this way isn't working anymore. It just happens nothing. I also tried to use .itemProvider { let url = .... return NSItemProvider(contentsOf: url) ?? NSItemProvider(object: url as NSURL) } but this doesn't work too. The same way with .onDrag works btw. .onDrag { let url = ....... // get the url with an internal function return NSItemProvider(object: url as NSURL) } but as I wrote, this will break the possibility to select or to use the primaryAction of the .contextMenu. Is this a bug? Or is my approach wrong and is there an alternative?
5
0
166
3w
macOS SwiftUI document app always shows file picker on startup
DESCRIPTION OF PROBLEM When my Document-based macOS SwiftUI app starts up, it always presents a document picker. I would like it to open any documents that were open when the app last quit, and if none were open, open an "Untitled" document. I understand that there is a setting in System Settings-> Desktop & Dock ("Close windows when quitting an application") that will cause windows to reopen when it is turned off, but I'd like to give users a chance to opt-in for reopening docs even when that is turned on, since it is difficult to find, on by default, and might not be the desired behavior for all apps. I don't see any way to get a list of currently open documents to persist them at shutdown. And even if that's considered a bad idea, I'd at least like a way to prevent the Document picker from being shown at startup and instead create an Untitled document if no documents were open. Ideally, I'd like a way to provide this functionality in SwiftUI that doesn't require macOS 15 or later STEPS TO REPRODUCE Create a SwiftUI macOS document application in Xcode using the provided template, Give it any name you want Run it, create a new ".exampletext" document, save it. Quit the app with the document open. Re-run the app, document picker is shown. Cancel the document picker and quit the app with no windows shown. Re-run the app, document picker is shown.
2
0
146
1w
MacOS SwiftUI access modelContext from menu (.commands)?
Adding an Import... menu item using .commands{CommandGroup... on DocumentGroup( ... ) { ContentView() } .commands { CommandGroup(replacing: .importExport) { Button("Import…") { isImporting = true } .keyboardShortcut("I", modifiers: .option) .fileImporter( isPresented: $isImporting, allowedContentTypes: [.commaSeparatedText], allowsMultipleSelection: false ) { result in switch result { case .success(let urls): print("File import success") ImportCSV.importCSV(url: urls, in: context) // This is the issue case .failure(let error): print("File import error: \(error)") } } } I could get this to work if I were not using DocumentGroup but instead programmatically creating the modelContext. using the shared modelContext in ImportCSV is not possible since that is not a View passing the context as shown above would work if I knew how to get the modelContext but does it even exist yet in Main? Is this the right place to put the commands code? Perhaps the best thing is to have a view appear on import, then used the shared modelContext. In Xcode menu File/Add Package Dependencies... opens a popup. How is that done?
1
0
97
1d
Fatal Exception: NSInternalInconsistencyException Attempting to select a view controller that isn't a child! (null)
When call: [UITabBarController setViewControllers:animated:] It crashed and raise an Fatal Exception: Fatal Exception: NSInternalInconsistencyException Attempting to select a view controller that isn't a child! (null) the crash stack is: Fatal Exception: NSInternalInconsistencyException 0 CoreFoundation 0x8408c __exceptionPreprocess 1 libobjc.A.dylib 0x172e4 objc_exception_throw 2 Foundation 0x82215c _userInfoForFileAndLine 3 UIKitCore 0x38a468 -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] 4 UIKitCore 0x3fa8a4 -[UITabBarController _setSelectedViewController:performUpdates:] 5 UIKitCore 0x3fa710 -[UITabBarController setSelectedIndex:] 6 UIKitCore 0x8a5fc +[UIView(Animation) performWithoutAnimation:] 7 UIKitCore 0x3e54e0 -[UITabBarController _setViewControllers:animated:] 8 UIKitCore 0x45d7a0 -[UITabBarController setViewControllers:animated:] And it appear sometimes, what's the root cause?
1
0
118
2d
How the input of UITextField is stored ?
When user enters in a textfield, is the input of textfield gets stored in a String ? If yes, then String in swift being immutable, as user keeps on typing does new memory for storing that text gets allocated with each key stroke ? And when we read users input by using delegate method textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) from textfield.text, we get users input in a String. Is it same storage as used by textfield for storing the user input on key stroke or is it some other storage with copy of the user's input in it? Or is UItextfield using a diffrent data structure (buffer) for storing the user input and when we do textfield.text, it gives a copy of data stored in original buffer?
1
0
117
1d
Discovered a bug where Alert button colors are changed by the tint modifier.
I used .tint(.yellow) to change the default back button color. However, I noticed that the color of the alert button text, except for .destructive, also changed. Is this a bug or Apple’s intended behavior? this occurs in iOS 18.1 and 18.1.1 Below is my code: // App struct TintTestApp: App { var body: some Scene { WindowGroup { MainView() .tint(.yellow) } } } // MainView var mainContent: some View { Text("Next") .foregroundStyle(.white) .onTapGesture { isShowingAlert = true } .alert("Go Next View", isPresented: $isShowingAlert) { Button("ok", role: .destructive) { isNextButtonTapped = true } Button("cancel", role: .cancel) { } } } thank you!
0
1
69
2d