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

Results with spotlight in Core Data is not all.
I'm using Core Data to save data. Then I wanna add spotlight support. self.spotlightDelegate = StorageSpotlightDelegate(forStoreWith: description, coordinator: container.persistentStoreCoordinator) let isSpotlightDisable = UserDefaults.standard.bool(forKey: "isSpotlightDisable") if !isSpotlightDisable { self.toggleSpotlightIndexing(enable: true) } public func toggleSpotlightIndexing(enable: Bool) { guard let spotlightDelegate = spotlightDelegate else { return } if enable { spotlightDelegate.startSpotlightIndexing() } else { spotlightDelegate.stopSpotlightIndexing() spotlightDelegate.deleteSpotlightIndex { error in if let error = error { print(error) } } } UserDefaults.standard.set(!enable, forKey: "isSpotlightDisable") } It works fine on an iOS15 device, but not work on iOS 17&18. On iOS 18 devices, I can search the data when the first time to added to Core Data. But if I stop spotlight indexing and restart again, the data is never be searched. How can I to solve this? And I noticed that the problem is also exists in another dictionary app.
0
0
108
1w
SwiftData with shared and private containers
I was hoping for an update of SwiftData which adopted the use of shared and public CloudKit containers, in the same way it does for the private CloudKit container. So firstly, a big request to any Apple devs reading, for this to be a thing! Secondly, what would be a sensible way of adding a shared container in CloudKit to an existing app that is already using SwiftData? Would it be possible to use the new DataStore method to manage CloudKit syncing with a public or shared container?
5
11
1.5k
Jun ’24
`SwiftUI.FileExportOperation.Error error 0` with `fileExporter` and `NSImage`
You'll have to forgive me, I am still pretty new to Swift, but I'm really struggling to figure out what I'm doing wrong or how I can fix it. I'm working on an app that generates an image from some views and then exports that image, but it always returns this very vague error: The operation couldn’t be completed. (SwiftUI.FileExportOperation.Error error 0.) Here's most of the program: import SwiftUI import UniformTypeIdentifiers struct ContentView: View { @State private var backgroundColor = Color.black @State private var fileExporterIsPresented = false @State private var image: NSImage? @State private var fileExporterErrorAlertIsPresented = false @State private var fileExporterErrorDescription: String? var body: some View { let wallpaper = Rectangle() .foregroundStyle(backgroundColor) .aspectRatio(16 / 9, contentMode: .fit) VStack { wallpaper .clipShape(.rect(cornerRadius: 10)) .overlay { RoundedRectangle(cornerRadius: 10) .strokeBorder(.separator, lineWidth: 5) } ColorPicker("Background Color", selection: $backgroundColor, supportsOpacity: false) Button("Generate Wallpaper") { let renderer = ImageRenderer(content: wallpaper.frame(width: 3840, height: 2160)) image = renderer.nsImage fileExporterIsPresented = true } .fileExporter( isPresented: $fileExporterIsPresented, item: image, contentTypes: [UTType.heic, UTType.png] ) { result in if case .failure(let error) = result { fileExporterErrorDescription = error.localizedDescription fileExporterErrorAlertIsPresented = true } } .alert("File Exporter Failure", isPresented: $fileExporterErrorAlertIsPresented, actions: { Button("OK") {} }, message: { if let fileExporterErrorDescription { Text(fileExporterErrorDescription) } }) .dialogSeverity(.critical) } .padding() } } #Preview { ContentView() }
1
0
140
2w
Scrolling is backwards with external devices when rotating to landscape mode
We recently converted an existing app to adopt scenes (for CarPlay). The app has one main view controller that presents a WKWebView to show our content. Everything works fine in both landscape and portait mode when swiping on the screen to scroll. But with an iPad using an external Magic Keyboard, once you rotate to landscape mode the scrolling gestures are reversed. Swiping vertically on the trackpad is scrolling the page horizontally and vice versa. When this happens an error like below is logged (this error also shows up when in portait mode, but scrolling works as expected): Unexpected window orientation: <UIWindow: 0x10370d8f0; orientation: landscapeLeft (4)> { hidden = NO; frame = {{0, 0}, {1180, 820}}; bounds = {{0, 0}, {1180, 820}}; ownsOrientation = NO; ownsOrientationTransform = NO; autorotationDisabled = NO; windowInterfaceOrientation = unknown (0); rootTransformOrientation = landscapeLeft (4); viewTransformOrientation = unknown (0); autorotationDisabled = NO; orientationVC = ... { providedSupportedOrientations = ( Pu Ll Lr Pd ); resolvedSupportedOrientations = ( Pu Ll Lr Pd ); canPreferOrientation = NO; }; }, event type: 6 It seems to suggest that while the view controller orientation is set correctly. It doesn't know what the orientation is for the window. I have been unable to figure out what would change with adopting scenes that would explain this behavior. I assume it has to do with the potential multi-window nature of it but haven't found any docs that describe how to ensure the window is setup to use the same orientation as the device. Any suggestions on things to check?
1
0
190
1w
Tile & Scale an Image
Working on a macOS app. I need to display user-added images as a background to the view, with all of: Tiling (auto repeat in both axes) Scaling (user-configured scale of the image) Offset (user-configured offset) I've been able to achieve scaling and offset with: Image(nsImage: nsImage) .scaleEffect(mapImage.scale) .offset(mapImage.offset) .frame(width: scaledImageSize.width, height: scaledImageSize.height) But when I try to incorporate tiling into that with .resizable(resizingMode: .tile) everything breaks. Is there a way to position the "anchor" of an image, scale it, and tile it in both axes to fill a container view?
1
0
120
2w
Crash calling UIHostingController from a Swift Package
Hello team, We recently found a EXC_BAD_ACCESS crash when using UIHostingControllers on a SPM local Package in our application. This is happening from time to time when we run the app on simulators using Debug configurations. Also, this issue is consistent when we run application tests, there is something weird that we found after making a research... If we disable app test target and only keep packages tests, the crash is not happening, but as soon as we re-enable the app test target from the test suite the crash returns. This is the full error message: Thread 1: EXC_BAD_ACCESS (code=1, address=0xbad4017) A bad access to memory terminated the process. Is this s known issue? We've been performing explorations for some days and couldn't find any real solution for this. A basic call on UIHostingController inside of a SPM local Package is enough to make the app crash, nothing custom being done: UIHostingController(rootView: MyView())
2
0
153
2w
ARVR RealityView Showing left Camera view Entity near more than the right view
I have this code to make ARVR Stereo View To Be Used in VR Box Or Google Cardboard, it uses iOS 18 New RealityView but for some reason the left side showing the Entity (Box) more near to the camera than the right side which make it not identical, I wonder is this a bug and need to be fixed or what ? thanx Here is the code import SwiftUI import RealityKit struct ContentView : View { let anchor1 = AnchorEntity(.camera) let anchor2 = AnchorEntity(.camera) var body: some View { HStack (spacing: 0){ MainView(anchor: anchor1) MainView(anchor: anchor2) } .background(.black) } } struct MainView : View { @State var anchor = AnchorEntity() var body: some View { RealityView { content in content.camera = .spatialTracking let item = ModelEntity(mesh: .generateBox(size: 0.25), materials: [SimpleMaterial()]) anchor.addChild(item) content.add(anchor) anchor.position.z = -1.0 anchor.orientation = .init(angle: .pi/4, axis:[0,1,1]) } } } And Here is the View
0
0
151
1w
How to set followsUserLocation and define a custom camera distance dynamically using MapKit for SwiftUI ?
Hello, I've created an app that follows the user as they navigate through public transport. I want the camera to follow the user and at the same time I want the camera distance (elevation) to change dynamically depending on speed and other factors. I've tried a first approach using camera keyframes, but I've noticed a lot of crashes when the app comes back to the foreground. .mapCameraKeyframeAnimator(trigger: cameraFrame) { camera in KeyframeTrack(\MapCamera.centerCoordinate) { LinearKeyframe(cameraFrame.center, duration: cameraFrame.duration, timingCurve: cameraFrame.curve) } KeyframeTrack(\MapCamera.distance) { LinearKeyframe(cameraFrame.distance, duration: cameraFrame.duration, timingCurve: cameraFrame.curve) } } Some logs mention wrong center coordinates (nan, nan) but when I print them, it's show me valid coordinates. I've also tried manually setting the camera for each position update, but the result is not smooth. position = .camera( .init(.init( lookingAtCenter: newPosition, fromDistance: cameraElevation, pitch: .zero, heading: .zero) ) ) What's the best way to achieve this?
0
0
104
2w
TitleLabel crash problem
Hello bro, I create a custom button like this way: UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.titleLabel.font = [UIFont fontWithName:fontName size:fontSize]; Then I receive any issue from the third crash collection platform: 0 libobjc.A.dylib 0x000000018fd1e694 _objc_moveWeak + 196 1 libobjc.A.dylib 0x000000018fd1e694 _objc_moveWeak + 196 2 CoreFoundation 0x0000000197e7da94 __CFXNotificationRegistrarAddObserver + 392 3 CoreFoundation 0x0000000197e7c864 _CFXNotificationRegistrarAdd + 580 4 CoreFoundation 0x0000000197e7c040 __CFXNotificationRegisterObserver + 248 5 UIKitCore 0x000000019a1b6c98 _UILabelCommonInit + 188 6 UIKitCore 0x000000019a1b69fc -[UILabel _commonInit] + 520 7 UIKitCore 0x000000019a1cdf88 -[UILabel initWithFrame:] + 56 8 UIKitCore 0x000000019a24824c -[UIButtonLabel _initWithFrame:button:] + 100 9 UIKitCore 0x000000019a247c14 -[UIButtonLegacyVisualProvider _newLabelWithFrame:] + 84 10 UIKitCore 0x000000019a15ee80 -[UIButtonLegacyVisualProvider _setupTitleViewRequestingLayout:] + 84 11 UIKitCore 0x000000019a15d81c -[UIButtonLegacyVisualProvider titleViewCreateIfNeeded:] + 44 12 UIKitCore 0x000000019a1cfa78 -[UIButton titleLabel] + 36 So would you please tell me how to avoid it?
0
0
148
2w
Using Generic SwiftData Modules
Hi, I have the view below that I want it to get any sort of SwiftData model and display and string property of that module, but I get the error mentioned below as well, also the preview have an error as below, how to fix it ? I know its little complicated. Error for the view GWidget " 'init(wrappedValue:)' is unavailable: The wrapped value must be an object that conforms to Observable " Error of preview " Cannot use explicit 'return' statement in the body of result builder 'ViewBuilder' " 3, Code #Preview { do { let configuration = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: Patient.self, configurations: configuration) let example = Patient(firstName: "Ammar S. Mitoori", mobileNumber: "+974 5515 7818", homePhone: "+974 5515 7818", email: "ammar.s.mitoori@gmail.com", bloodType: "O+") // Pass the model (Patient) and the keyPath to the bloodType property return GWidget(model: example, keyPath: \Patient.bloodType) .modelContainer(container) } catch { fatalError("Fatal Error") } } 4. Code for the Gwidget View ```import SwiftUI import SwiftData struct GWidget<T>: View { @Bindable var model: T var keyPath: KeyPath<T, String> // Key path to any string property // Variables for the modified string and the last character var bloodTypeWithoutLast: String { let bloodType = model[keyPath: keyPath] return String(bloodType.dropLast()) } var lastCharacter: String { let bloodType = model[keyPath: keyPath] return String(bloodType.suffix(1)) } var body: some View { VStack(alignment: .leading) { Text("Blood Type") .font(.footnote) .foregroundStyle(sysPrimery07) HStack (alignment: .lastTextBaseline) { Text(bloodTypeWithoutLast) .fontWeight(.bold) .font(.title2) .foregroundStyle(sysPrimery07) VStack(alignment: .leading, spacing: -5) { Text(lastCharacter) .fontWeight(.bold) Text(lastCharacter == "+" ? "Positive" : "Negative") } .font(.caption2) .foregroundStyle(lastCharacter == "+" ? .green : .pink) } } } }
3
0
215
Oct ’24
SwifttData Record Update
Hi When connecting a SwiftData module property to a SwiftUI view such as a text field and the field changes by user the property get updated in the SwiftData database, now suppose I want to run a validation code or delay updates to Database till use click a submit button how to do that ? delay those auto updates if we can name it ? Kind Regards Code Example import SwiftUI import SwiftData struct GListSel2: View { @Bindable var patient: Patient var body: some View { HStack { TextField("Gender", text: $patient.gender) } } }
1
0
106
2w
Loading object on NSItemProvider is delayed until drop exit
I have drag-and-drop functionality in the macOS app built with SwiftUI. Since macOS 15 there is an issue with it, because as I found out, the completion block of loadObject method on NSItemProvider is not called until dropExited delegate method is called (see simplified code example below). It causes very strange behavior in my app, for one of the most important features, and I am looking for a way to fix it as soon as possible. Is anyone seeing the same issue? I saw there was a bug with drag and drop on iOS 18, which seems to be fixed in 18.1. Anyone from Apple can say anything about this change in behaviour? @Observable // Because it is injected via environment. final class DragAndDropDelegate<T: Codable>: DropDelegate { func dropEntered(info: DropInfo) { // Is called as expected. guard let itemProvider = info.itemProviders(for: [UTType.data]).first else { return } itemProvider.loadObject(ofClass: DraggableObject<T>.self) { [weak self] (object, error) in // This is only called after dropExited delegate method is called !!! // Before macOS 15.0 it is called quickly after the loadObject method invokation. asyncOnMainThread { guard let self, let draggableObject = object as? DraggableObject<T> else { return } self.onEnter?(draggableObject.object, info.location) } } } func dropExited(info: DropInfo) { // Is called as expected. } }
4
0
162
3w
Task, onAppear, onDisappear modifiers run twice
I've run into an issue with my app that I've been able to narrow down to a small reproducer. Any time there is a task associated with the DetailView and you "pop to top", onAppear is called again and the task is re-run. Why is that? Is this a SwiftUI bug? It doesn't happen on iOS 17, only 18. import SwiftUI @Observable class Store { var shown: Bool = true } @main struct MyApp: App { @State private var store = Store() var body: some Scene { WindowGroup { if store.shown { ContentView() } else { EmptyView() } } .environment(store) } } struct ContentView: View { var body: some View { NavigationView { NavigationLink(destination: DetailView()) { Text("Go to Detail View") } } } } struct DetailView: View { @Environment(Store.self) private var store init() { print("DetailView initialized") } var body: some View { Button("Pop to top") { store.shown = false } .task { print("DetailView task executed") } .onAppear { print("DetailView appeared") } .onDisappear { print("DetailView disappeared") } } }
3
0
272
Oct ’24
Updating Sequoia Beta on External Drive
For the last 2 version (18.2 beta 1 and 18.2. beta 2) I haven't been able to successfully update to either of them. I have been running Sequoia on an external drive for testing purposes and didn't have this problem with any of the 18.1 versions. I'm currently on 18.1 (public) and when I download the update for 18.2 beta 2, the update appears to run (takes about 30 mins), preparing update, the restarts. When the Mac restarts, it just boots straight back to 18.1 without having applied the update.
0
0
97
2w