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

How to connect a @Parameter of a Tip to my app's state?
I have an observable object which is a model a view. I also have a Tip (from TipKit) with @Parameter and a rule. The source of truth for the state is in the observable object, however the Tip needs to be updated when state changes. So how do I bind between the two? The way I was thinking was to sink updates from objectWillChange and check if Tips parameter needs to be updated or add didSet if it a @Published property. But I am not sure this is the best practice. Schematic example: class MyModel: ObservableObject { struct TapSubmitTip: Tip { @Parameter static var isSubmitButtonEnabled: Bool = false var title: Text { Text("Tap \"Submit\" to confirm your selection.") } var rules: [Rule] { #Rule(Self.$isSubmitButtonEnabled) { $0 == true } } } let tapSubmitTip = TapSubmitTip() var objectWillChangeCancallable: AnyCancellable! // Used by the view to enable or disable the button var isSubmitButtonEnabled: Bool { // Some logic to determine if button should be enabled. } init() { objectWillChangeCancallable = objectWillChange.sink { [weak self] void in guard let self else { return } if isSubmitButtonEnabled { TapSubmitTip.isSubmitButtonEnabled = true } } } ... // Call objectWillChange or update published properties as needed. ... }
0
0
412
Dec ’24
SwiftUI glitch with coloreffect shader & orientation change
Hi, I have the following swiftUI code: Image(uiImage: image) .resizable() .aspectRatio(contentMode: .fit) .colorEffect(ShaderLibrary.AlphaConvert()) and the following shader: [[ stitchable ]] half4 AlphaConvert(float2 position, half4 currentColor) { return half4(currentColor.r>0.5,currentColor.r<=0.5,0,(currentColor.r>0.5)); } I am loading a full-res image from my photo library (24MP)... The image initially displays fine, with portions of the image red, and the rest black (due to alpha blending)... However, after rotating the device, I get an image that is a combination of red&green... Note, that the green pixels from the shader have alpha 0, hence, should never be seen. Is there something special that needs to be done on orientation changes so that the shader works fine?
0
0
401
Dec ’24
Separate RealityView inside a RealityView attachment
Hi, I am having some troubles creating a "nested" RealityView content using MapKit attachment. I am building a visionOS app that has horizontal MapKit map as an attachment to RealityView. I want to display 3D pins on that map, therefore I am using native map annotation and inside of these annotations, I create a new RealityView just for the 3D pin. This worked completely fine, unitil I wanted to have those RealityViews interact with each other. By interaction of those RealityViews I mean that I wanted to group entities from the first "main" RealityViews content with the 3D pins using ModelSortGroupComponent. Why I want this? I want to make the map circular, that is not a problem. Problem is that when I move the map with 3D pins, these pins have their own RealityView space and are only bounded by volumetric window dimensions. What happes is that these pins float next to the map (shown on attached image). So I came up with this solution: create a custom "toroid" like 3D entity model that occludes the pins that go outside the map region. In order to occlude only the pins, I need to use ModelSortGroupComponent to group the "toroid" entity with 3D pins entities (as described in another forum thread). To summarize: need the content of the superior RealityView to interact with map attachment annotations RealityView content in order to group them. There might be of course another, better way to achieve my whole goal, so I would naturally appreciate any help or guidance. Image below showing 3D pins on circular map. Since pins RealityView does no know anything about other RealityViews, it just overlows and hangs in space until is cropped by volumetric window boundary. Simplified code: var body: some View { let modelSortGroup = ModelSortGroup(depthPass: .prePass) RealityView { content, attachments in var mainEntity = Entity() // My other entities here... if let mapAttachment = attachments.entity(for: "mapAttachment") { // Edit map properties, position, horizontal layout etc. mainEntity.addChild(mapAttachment) } // Create and add to content mask "toroid" entity mapMaskEntity. Use OcclusionMaterial() material. mapMaskEntity.components.set(ModelSortGroupComponent(group: modelSortGroup, order: 0)) // For all pins, somehow also set the group // 3DPinEntity.components.set(ModelSortGroupComponent(group: modelSortGroup, order: 1)) content.add(mainEntity) } attachments: { Attachment(id: "mapAttachment") { Map { ForEach(mapViewModel.clusters, id: \.id) { cluster in Annotation("", coordinate: cluster.coordinate) { MapPin3DView(cluster: cluster) } } } .clipShape(Circle()) } } } // MapPin3DView is an map annotation view that includes a model of 3D pin and some details like image etc., uses RealityView. struct MapPin3DView: View { var body: some View { RealityView { content in // 3D pin entities... } } }
1
0
503
Dec ’24
Why can NavigationStacks be nested in a sheet but not an overlay?
If two NavigationStacks are nested with the inner stack in a sheet NavigationLinks in the inner stack open as expected in the inner stack. struct ContentView: View { var body: some View { NavigationStack { Color.clear .sheet(isPresented: .constant(true)) { NavigationStack { ExampleList() .navigationTitle("Inner Navigation Stack") } .presentationDetents([.medium]) } .navigationTitle("Outer Navigation Stack") } } } If I try the same with an overlay instead of a sheet, NavigationLinks in the inner stack unexpectedly open in the outer stack. struct ContentView: View { var body: some View { NavigationStack { Color.clear .overlay(alignment: .bottomTrailing) { NavigationStack { ExampleList() .navigationTitle("Inner Navigation Stack") } .frame(width: 200, height: 250) .border(.black, width: 5) .padding() .presentationDetents([.medium]) } .navigationTitle("Outer Navigation Stack") } } } Even the navigation title for the outer stack is being overridden by the inner stack's navigation title. TLDR What magic is sheet using that allows for nested NavigationStacks and how might I approach getting this to work in an overlay? iOS 18.2 Xcode 16.2 The definition of ExampleList for reproducibility: struct ExampleList: View { var body: some View { List(1..<5) { number in NavigationLink("\(number)") { Text("\(number)") .font(.largeTitle) } } } }
1
0
503
Jan ’25
SwiftUI Menu with NavigationLinks inside overall NavigationStack
I've read all previous posts on this topic but none seem to address what I'm seeing for iOS 16 and using NavigationStack. I'm also using an overall @EnvironmentObject for navigation state. I have a split view app. In the detail section, I have a NavigationStack surrounding the detail view. Within the detail view (MyView), there is a base view with a "+" button in the toolbar to create a new entity. That opens NewEntityView where I show a grid of buttons for the user to select a type to create a new entity before moving to NewEntityView to fill in the details for the entity. The top row of the grid of buttons takes the user straight to the NewEntityView with a NavigationLink. These work fine. The next row of buttons present a menu of sub-types and then should take the user to the NewEntityView view. These buttons do not work. Code (simplified to not have clutter): SplitViewDetailView: struct SplitViewDetailView: View { @EnvironmentObject var navigationManager: NavigationStateManager @Binding var selectedCategory: Route? var body: some View { NavigationStack(path: $navigationManager.routes) { // other irrelevant stuff MyView() } .environmentObject(navigationManager) .navigationDestination(for: Route.self) { $0 } } } MyView: struct MyView: View { @EnvironmentObject var navigationManager: NavigationStateManager var body: some View { List { // other stuff } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: {}, label: { NavigationLink(value: Route.newTypeSelect) { Image(systemName: "plus") .frame(width: 44, height: 44) } } ) } } .navigationDestination(for: Route.self) { $0 } } SelectTypeView: struct SelectTypeView: View { var body: some View { ZStack { VStack { // Top row with no subtypes HStack { ForEach (topRows, id: \.self) { type in NavigationLink(value: Route.newEntityDetails(type.rawValue)) { <-- these work Text(type) } } } HStack { ForEach (middleRow, id: \.self) { type in Menu { ForEach (subtype[type], id: \.self) { sub in NavigationLink(value: Route.newEntityDetails(sub.rawValue)) { <-- these go nowhere Text(sub) } } } label: { Text(type) } } } } } } } NavigationStateManager: class NavigationStateManager: ObservableObject { @Published var routes = [Route]() // other stuff } And Route: enum Route: Identifiable { var id: UUID { UUID() } case newTypeSelect case newEntityDetails(String) } extension Route: View { var body: some View { switch self { case .newTypeSelect: SelectTypeView() case .newEntityDetails(let type): NewEntityView(selectedType: type) } } } The menus show up fine but tapping on an item does nothing. I've attempted to wrap the menu in its own NavigationStack but that is rejected stating it is already in one defined by a parent view. I've tried making the links Buttons with destinations and those are also rejected. What is the newest/best way to present a menu with NavigationLinks? One doesn't simply wrap the menu in a NavigationView if one is using a NavigationStack?
1
0
1.2k
Jan ’25
CoreAutoLayout -[NSISEngine positiveErrorVarForBrokenConstraintWithMarker:errorVar:]
My App always encounter with CoreAutoLayout invade My SnapKit layout constraint as follow: popBgView.snp.makeConstraints { make in make.centerY.equalToSuperview() make.leading.equalTo(assistantTeacherView.snp.trailing).offset(.isiPad ? -50 : -40) if TTLGlobalConstants.isCompactScreen320 { make.width.lessThanOrEqualTo(300) } else { let widthRatio = .isiPad ? 494.0 / 1024.0 : 434.0 / 812.0 make.width.lessThanOrEqualTo(TTLGlobalConstants.screenWidth * widthRatio) } bubbleViewRightConstraint = make.trailing.equalToSuperview().constraint } ..... popBgView.addSubview(functionView) msgLabel.snp.remakeConstraints { make in make.leading.equalToSuperview().inset(Metric.msgLabelHorizantalInset) make.centerY.equalToSuperview() make.trailing.lessThanOrEqualToSuperview().inset(Metric.msgLabelHorizantalInset) make.top.equalTo(Metric.msgLabelVerticalInset) } functionView.snp.makeConstraints { make in make.leading.equalTo(msgLabel.snp.trailing).offset(Metric.msgLabelFunctionSpacing) make.centerY.equalToSuperview() make.trailing.equalToSuperview().offset(-Metric.msgLabelHorizantalInset) } msgLabel and functionView superview is popBgView However, when I try remove from superview for functionView, There is low probability crash: OS Version: iOS 16.1.1 (20B101) Report Version: 104 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: SEGV_NOOP Crashed Thread: 0 Application Specific Information: Exception 1, Code 1, Subcode 14967683541490370463 > KERN_INVALID_ADDRESS at 0xcfb7e4e0f8fe879f. Thread 0 Crashed: 0 CoreAutoLayout 0x382555f44 -[NSISEngine positiveErrorVarForBrokenConstraintWithMarker:errorVar:] 1 CoreAutoLayout 0x382555e9c -[NSISEngine positiveErrorVarForBrokenConstraintWithMarker:errorVar:] 2 CoreAutoLayout 0x3825557e4 -[NSISEngine removeConstraintWithMarker:] 3 CoreAutoLayout 0x382555198 -[NSLayoutConstraint _removeFromEngine:] 4 UIKitCore 0x34d87961c __57-[UIView _switchToLayoutEngine:]_block_invoke 5 CoreAutoLayout 0x382556e8c -[NSISEngine withBehaviors:performModifications:] 6 UIKitCore 0x34d8a1c38 -[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:] 7 UIKitCore 0x34d7f01b0 __57-[UIView _switchToLayoutEngine:]_block_invoke_2 8 UIKitCore 0x34d879770 __57-[UIView _switchToLayoutEngine:]_block_invoke 9 CoreAutoLayout 0x382556e8c -[NSISEngine withBehaviors:performModifications:] 10 UIKitCore 0x34d8a1c38 -[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:] 11 UIKitCore 0x34d8a1848 __45-[UIView _postMovedFromSuperview:]_block_invoke 12 UIKitCore 0x34e7ff8d0 -[UIView _postMovedFromSuperview:] 13 UIKitCore 0x34d85e3c8 __UIViewWasRemovedFromSuperview 14 UIKitCore 0x34d85b1a4 -[UIView(Hierarchy) removeFromSuperview] 15 Collie-iPad 0x203001550 [inlined] InClassAssistantView.functionView.didset (InClassAssistantView.swift:105)
Topic: UI Frameworks SubTopic: UIKit
0
0
241
Jan ’25
Validate drag operations with Transferable
Let's say I want to build a simple photo management app on Mac or iPad with Swift UI. This app has multi-window support. My photos are organized inside albums. I should be able to drag photos between windows from one album to another. I struggle to get this working properly with Swift UI. Writing modern code I would like to use Transferable. Let's say my photos are not real files. So I can't use a FileRepresentation. Instead I use CodableRepresentation and encode an identifier. This identifier is later used to drive the move operation between folders. I ran into some limitations here Transferable seems to be meant for copy-like Drag & Drop operations. I have no possible to get a "move" cursor on macOS (it's always the copy cursor with the green + sign). Also the API reads like it is about importing/exporting – not moving. When using dropDestination on ForEach, I completely lack the possibility to deny a drop (e.g. when a photo is already part of the album). I'd like to have modifier key to switch between copying and moving. Sometimes a drop should be redirected to a different index. How to do that? Is there any chance to do this with Transferable? It even doesn't seem to be easy with NSItemProvider and onDrop/onDrag? Or should we still use a plain old UICollectionView/NSCollectionView, if we want to have more sophisticated control over drag/drop validation?
4
0
440
Jan ’25
SwiftUI crashes EXC_BREAKPOINT at _dispatch_semaphore_dispose
Based on crash reports for our app in production, we're seeing these SwiftUI crashes but couldn't figure out why it is there. These crashes are pretty frequent (>20 crashed per day). Would really appreciate it if anyone has any insight on why this happens. Based on the stacktrace, i can't really find anything that links back to our app (replaced with MyApp in the stacktrace). Thank you in advance! Crashed: com.apple.main-thread 0 libdispatch.dylib 0x39dcc _dispatch_semaphore_dispose.cold.1 + 40 1 libdispatch.dylib 0x4c1c _dispatch_semaphore_signal_slow + 82 2 libdispatch.dylib 0x2d30 _dispatch_dispose + 208 3 SwiftUICore 0x77f788 destroy for StoredLocationBase.Data + 64 4 libswiftCore.dylib 0x3b56fc swift_arrayDestroy + 196 5 libswiftCore.dylib 0x13a60 UnsafeMutablePointer.deinitialize(count:) + 40 6 SwiftUICore 0x95f374 AtomicBuffer.deinit + 124 7 SwiftUICore 0x95f39c AtomicBuffer.__deallocating_deinit + 16 8 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 9 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 10 SwiftUICore 0x77e53c StoredLocation.deinit + 32 11 SwiftUICore 0x77e564 StoredLocation.__deallocating_deinit + 16 12 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 13 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 14 MyApp 0x1673338 objectdestroyTm + 6922196 15 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 16 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 17 SwiftUICore 0x650290 _AppearanceActionModifier.MergedBox.__deallocating_deinit + 32 18 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 19 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 20 SwiftUICore 0x651b44 closure #1 in _AppearanceActionModifier.MergedBox.update()partial apply + 28 21 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 22 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 23 libswiftCore.dylib 0x3b56fc swift_arrayDestroy + 196 24 libswiftCore.dylib 0xa2a54 _ContiguousArrayStorage.__deallocating_deinit + 96 25 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 26 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 27 SwiftUICore 0x4a6c4c type metadata accessor for _ContiguousArrayStorage<CVarArg> + 120 28 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 29 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 30 SwiftUICore 0x4a5d88 static Update.dispatchActions() + 1332 31 SwiftUICore 0xa0db28 closure #2 in closure #1 in ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) + 132 32 SwiftUICore 0xa0d928 closure #1 in ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) + 708 33 SwiftUICore 0xa0b0d4 ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) + 556 34 SwiftUI 0x8f1634 UIHostingViewBase.renderForPreferences(updateDisplayList:) + 168 35 SwiftUI 0x8f495c closure #1 in UIHostingViewBase.requestImmediateUpdate() + 72 36 SwiftUI 0xcc700 thunk for @escaping @callee_guaranteed () -> () + 36 37 libdispatch.dylib 0x2370 _dispatch_call_block_and_release + 32 38 libdispatch.dylib 0x40d0 _dispatch_client_callout + 20 39 libdispatch.dylib 0x129e0 _dispatch_main_queue_drain + 980 40 libdispatch.dylib 0x125fc _dispatch_main_queue_callback_4CF + 44 41 CoreFoundation 0x56204 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 42 CoreFoundation 0x53440 __CFRunLoopRun + 1996 43 CoreFoundation 0x52830 CFRunLoopRunSpecific + 588 44 GraphicsServices 0x11c4 GSEventRunModal + 164 45 UIKitCore 0x3d2eb0 -[UIApplication _run] + 816 46 UIKitCore 0x4815b4 UIApplicationMain + 340 47 SwiftUI 0x101f98 closure #1 in KitRendererCommon(_:) + 168 48 SwiftUI 0xe2664 runApp<A>(_:) + 100 49 SwiftUI 0xe5490 static App.main() + 180 50 MyApp 0x8a7828 main + 4340250664 (MyApp.swift:4340250664) 51 ??? 0x1ba496ec8 (Missing)
0
0
527
Jan ’25
Screen capture notification in MacOs catalyst
We have a IOS app and we are using the same app for Mac Catalyst. In IOS we are able to detect when user take the screenshot using UIApplicationUserDidTakeScreenshotNotification. But in MACCatalyst it is not working. As per docs UIApplicationUserDidTakeScreenshotNotification and UIScreenCapturedDidChangeNotification are both supported for MacCatalyst 13.1+. But I am not getting screen shot notifications using both
3
0
496
Feb ’25
Rectangle change size by swipe
Hi,, How can I make a rectangle become taller as I swipe down on my trackpad?" struct BlueRectangleView: View { var body: some View { VStack { Rectangle() .fill(Color.blue) .frame(width: 200, height: 100) .cornerRadius(10) .shadow(radius: 5) .padding() } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.white) } } struct BlueRectangleView_Previews: PreviewProvider { static var previews: some View { BlueRectangleView() } }
2
0
276
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
393
Jan ’25
Why timer isn't working with button in SwiftUI
.onReceive construction isn't working with button long press gesture but tap is working, it increases count by 1. Construction should increase count every 0.5 seconds if button pressed struct Test: View { @State private var count = 0 @State private var isLongPressed = false var body: some View { VStack { Text("Count: \(count)") Button("Increase") { count += 1 print("Button tapped") } .onLongPressGesture { isLongPressed = true print("Long press started") } .onLongPressGesture(minimumDuration: 0) { isLongPressed = false print("Long press ended") } } .onReceive(Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()) { _ in if isLongPressed { count += 1 print("Count increased: \(count)") } } } }
1
0
384
Jan ’25
When accessing a compressed file in the iCloud Drive from the Files app, an error occurs.
I am trying to upload a ZIP file, created by compressing other files in iCloud Drive through the Files app, using UIDocumentPicker. However, errors like those described in Test 1 and Test 2 in the sample code are occurring. import UIKit class ViewController: UIViewController,UIDocumentPickerDelegate { override func viewDidLoad() { super.viewDidLoad() } @IBAction func openDocumentPicker(_ sender: Any) { // Test 1 // let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: true) // When clicking the "Open" button, there is no response, and the following error occurs. /* Failed to copy the imported file into the local container ((null)) Tried to call delegate -documentBrowser:didPickDocumentURLs: with an empty array of items. This indicates the items failed to be prepared and materialized on disk: ( "<DOCItemBookmark: 0x303ad2fc0> FPItem=(null)" ) */ // Test 2 let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.item]) // When using the regular mode instead of the copy mode, // the "Open" button works, and the selectedFileURL is correctly retrieved. // However, even after using startAccessingSecurityScopedResource, // attempting to read the file results in the following error. /* Error reading file: Error Domain=NSCocoaErrorDomain Code=257 "The file “archive 4.zip” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/samplefiles/archive 4.zip, NSURL=file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/%E1%84%89%E1%85%A2%E1%86%B7%E1%84%91%E1%85%B3%E1%86%AF%E1%84%91%E1%85%A1%E1%84%8B%E1%85%B5%E1%86%AF/%E1%84%8B%E1%85%A1%E1%84%8F%E1%85%A1%E1%84%8B%E1%85%B5%E1%84%87%E1%85%B3%204.zip, NSUnderlyingError=0x300bedbf0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"} */ documentPicker.delegate = self documentPicker.allowsMultipleSelection = true self.present(documentPicker, animated: true, completion: nil) } func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard urls.isEmpty == false else { print("no urls") return } //Test2 for selectedFileURL in urls { // Start accessing the security-scoped resource if selectedFileURL.startAccessingSecurityScopedResource() { defer { selectedFileURL.stopAccessingSecurityScopedResource() } // Perform operations on the file do { let fileCoordinator = NSFileCoordinator() var error: NSError? fileCoordinator.coordinate(readingItemAt: selectedFileURL, options: [], error: &error) { (newURL) in do { let fileData = try Data(contentsOf: newURL) // Process the file data print("File data read successfully") } catch { print("Error reading file: \(error)") } } if let error = error { print("Error coordinating file access: \(error)") } } catch { print("Error reading file: \(error)") } } else { print("Failed to access security-scoped resource") } } } It seems that there might be an issue with the compressed ZIP file. How can this be resolved?
Topic: UI Frameworks SubTopic: General
1
0
800
Jan ’25
@Binding var updates only once
I have a very annoying problem editing a property of one of my model structs: the binding var (subject) property (gender) is updated only once by a selection list. The first time I use my control, all works correctly; from the second time on, nothing happens (not even an .onChange() placed for debug... it simply doesn't fire up). EVEN MORE STRANGE BEHAVIOR: The SAME control, copied inside an Apple sample projects works perfectly (Recipies Sample, downloaded from Apple Developer site). This sample project is, I guess, at least two years old, still with @ObservableObject, @Publish, ...and so on, that I converted to @Observable protocol. FINAL CHERRY ON THE CAKE: THE SAME sample Project, copied ASIS into a new Xcode projects, doesn't work anymore! It seems an error buried deep inside Xcode compiler optimizations (maybe to avoid unnecessary views redraw carried too far...). Anyway: I'm asking for help, because I'm not able to see any reason for this behavior and - just to add a bit of frustration - a working project developed with Xcode 15, without any problem (Stager, available on the App Store), reopenend with Xcode 16 acquires the same odd behavior. Any Apple developer can help? Many thanks in advace Simplified code follows (I made a new project just with the few things needed to show the case) MODEL import Foundation import SwiftUI enum Gender : String, Codable, CaseIterable, Equatable { case male = "M" case female = "F" case nonbinary = "N" case unknown = "U" var description : String { switch self { case .male : "Male" case .female : "Female" case .nonbinary : "Not binary" case .unknown : "Unknown" } } var iconName : String { "iconGender\(self.rawValue)" } } struct Subject : Identifiable, Codable, Equatable, Hashable { var id : Int var name : String var surname : String var nickName : String // Identificativo alternativo all’anagrafica var gender : Gender // Sesso del soggetto [ M | F | * ] var imageName : String { "foto" + self.nickName.replacingOccurrences(of: " ", with: "") + ".jpg" } static func == (lhs: Subject, rhs: Subject) -> Bool { return (lhs.id, lhs.nickName, lhs.surname, lhs.name) == (rhs.id, rhs.nickName, rhs.surname, rhs.name) } static func emptySubject() -> Subject { return Subject(id: -1, name: "", surname: "", nickName: "", gender: .unknown) } func hash(into hasher: inout Hasher) { hasher.combine(id) hasher.combine(nickName) hasher.combine(surname) hasher.combine(name) } } CONTROL import SwiftUI struct FormPickerGender: View { @Binding var value : Gender let isEdit : Bool @State var presentPicker : Bool = false var body: some View { HStack { Text("Gender:").foregroundStyle(.gray).italic() if isEdit { Image(systemName: "text.magnifyingglass") .foregroundStyle(.tint) .onTapGesture { presentPicker = true } } Text("\(value.description)") } .sheet(isPresented: $presentPicker, content: { PickGender(currentGender: $value) }) } } struct PickGender: View { @Environment(\.dismiss) var dismiss @Binding var currentGender : Gender var body: some View { Text("Gender selection") .font(.title2) .foregroundStyle(.tint) Button("Cancel") { dismiss() } .buttonBorderShape(.capsule) List { ForEach(Gender.allCases, id: \.self) { genderCase in HStack { Image("\(genderCase.iconName)") if currentGender == genderCase { Text(genderCase.description) .font(.title3) .foregroundStyle(.blue) } else { Text(genderCase.description) .font(.title3) } Spacer() } .onTapGesture { currentGender = genderCase dismiss() } } .listRowInsets(EdgeInsets(top: 10, leading: 50, bottom: 10, trailing: 50)) } } } struct GenderPreviewWrapper: View { @State var subject = Subject.emptySubject() var body: some View { Form { FormPickerGender(value: $subject.gender, isEdit: true) } } } #Preview { return GenderPreviewWrapper() } Just for completion... If instead of $subject.gender, I use a state variable valued with gender and then $stateGender it works, but to create a specific state var for EACH property of a structure, seems to me to nullify the concept itself of struct: why bother to foreseen properties, if you can't manage them as a whole? Probably the solution will be to create a specific CLASS object of the STRUCT object, just for edit... something like : static func <STRUCT>.getEditObject() -> classObject static func <CLASS>.getStructObject() -> structObject ...once again: why have structs?
Topic: UI Frameworks SubTopic: SwiftUI
5
0
333
Dec ’24
ShareLink does not prompt inside of fullScreenCover
When I try to launch a ShareLink from within a fullScreenCover, I get the following error: Attempt to present <UIActivityViewController: 0x105e6a400> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x1053a37c0> (from <_TtGC7SwiftUI19UIHostingControllerVVS_7TabItem8RootView_: 0x105eb8a00>) which is already presenting <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x114890000> Seems like a bug, has anyone else encountered this or found a way around it?
1
0
204
Jan ’25
Unable to Use DeviceActivityReport to Show Screen Time in App
Hi team. I am working on an app that uses the Screen Time API. I got access to the family controls (distribution) capability through the request process for my main app. I added a DeviceActivityReport extension in XCode, but haven't been able to get the extension to show up on the screen. I noticed that the extension only has the development version of the family controls capability available. Is this the source of my errors? I was able to get the screen time displayed in a test app I built where both the main app and extension used the development version of the capability, which led me to believe that discrepancy could be the issue. Let me know if there is anything I can provide to help in the debugging process. I didn't send a minimal example in this request due to the fact that I would have to remove most of my functionality to create a "minimal" example (since the signing is only for my main app), but I can do that if needed. Thanks! I looked through the logs in the console for the phone (I'm testing on a real iPhone 13 Pro Max), but didn't see anything that popped out after looking (not exactly sure what to look for though). STEPS TO REPRODUCE: Create an app with the Family Controls, Distribution capability. Then create the DeviceActivityReport with the Family Control, Development capability. Attempt to see the DeviceActivityReport in the main app. NOTE: I was successfully able to create a minimal test app completely separately that used the Development versions of the capabilities for both with the exact same extension code. That's why I think the issue could be due to the capability version discrepancy.
5
0
398
Jan ’25
Performance Regression: iPhone Version 18.2 Takes More Time to Render Volume Than Version 18.1
Hello, I am experiencing a performance regression in my application when rendering volumes on iPhone. Specifically, I have noticed that iOS version 18.2 takes significantly more time for each render cycle as compared to iOS 18.1. Details: Affected Versions: iOS version 18.2 iOS version 18.1 (baseline for comparison) Issue Description: In iOS version 18.2, the time taken to render volumes has increased compared to iOS version 18.1. This performance regression is affecting the user experience in my application. Test Example: https://www.cornerstonejs.org/live-examples/volumeviewport3d Steps to Reproduce: Load the above test example on an iPhone running version 18.2 using safari. Perform volume rendering using the provided dataset. Measure the time taken by volume for each rotate or drag action. Repeat the same steps on an iPhone running version 18.1 for comparison. Additional Information: Device Model Tested: iPhone12, iPhone13, iPhone14 iOS Version With Issue: 18.2 18.3(Beta) I would appreciate any insights or suggestions on how to address this performance regression. If additional information is needed, please let me know. Thank you.
1
0
610
Dec ’24
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