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

TextField with Double or Int not binding back ?
Hi there, In a SwiftUI View, I have a @State var test: Double? and a TextField like that : TextField("Test", value: $test, formatter: NumberFormatter()) the variable test is constantly nil and never being populated with the Double value of the entered text. Is it a bug or a concept error of mine ?? Thanks!
2
1
1.9k
Jul ’22
SwiftUI slider in accessibilityRepresentation & XCUITest slider's normalizedSliderPosition
Hi everybody, given the following case using SwiftUI: Button("testButton", action: noop) .accessibilityRepresentation{representation: { Slider(value: $sliderData.sliderValue) }) .accessibilityIdentifier("testSlider") I'm trying to control the slider using XCUITest via slider.adjust(toNormalizedSliderPosition: 0.2) and receive the following error message: Failed: Unable to get expected attributes for slider, found { "XC_kAXXCAttributeMaxScrubberPosition" = { X = 0; Y = 0; }; "XC_kAXXCAttributeMinScrubberPosition" = { X = 0; Y = 0; }; Similarly, print (slider.normalizedSliderPosition) leads to the error message "Failed to determine current position of slider "0 %". Is there a way to set and read the value of accessibilityRepresentation-Sliders with XCUITest? Thanks!
2
1
1.3k
Jul ’22
SwiftUI: Bottom sheet from the iPhone "find my" and "maps" app
I would like to include the bottom sheet from the iPhone "find my" and "maps" app in my app. During my research I came across the new modifier .presentationDetents for sheets. The only problem here is that you can no longer interact with the main screen when the sheet is active. In my app, however, I would like the sheet to be active all the time like in the iPhone apps mentioned and that you can still interact with the main screen like in the iPhone apps with the map. I would be very happy about help. Greetings
10
4
4.3k
Aug ’22
Keep Menu Open on SwiftUI?
Is there a way to keep the menu open after tapping on a button or toggle inside it instead of automatically minimizing it on every tap? This isn't a feature that's going to production ever, by the way. My code is something like this: struct MyView: View {     @State var toggleA = true     @State var toggleB = true     @State var toggleC = true     var body: some View {         NavigationView {             SwiftUI.Form {                 Text("Hello")             }             .navigationTitle("My View")             .navigationBarTitleDisplayMode(.inline)             .navigationBarItems(trailing: {                 Menu {                     Toggle("A", isOn: $toggleA)                     Toggle("B", isOn: $toggleB)                     Toggle("C", isOn: $toggleC)                 } label: {                     Image(systemName: "ellipsis.circle")                 }             }())         }     } } struct Preview: PreviewProvider {     static var previews: some View {         MyView()     } }
3
2
1.3k
Aug ’22
"UI unresponsiveness" warning on @main
I'm seeing a runtime warning in Xcode 14 Beta 5 that says "This method should not be called on the main thread as it may lead to UI unresponsiveness." This is happening on the @main entry point of my app. See below: The warning shown gives me no insight into what's actually going wrong. I think it may be due to some Core Location code that runs when the app first opens, but is there a way for me to get some more insight into what's causing this? Or is this possibly an Xcode 14/iOS 16 bug, and this is not an issue to worry about? I'm not getting any warnings on Xcode 13/iOS 15.
75
27
75k
Aug ’22
SwiftUI: Conditionally switching between .fullScreenCover() and .sheet() not working
I'd like to use .fullScreenCover() or .sheet() to present a View, depending on the current horizontalSizeClass. If starting the following code in an iPhone (in portrait mode = .compact) or in an iPad (= .regular), the View is correctly displayed in a Sheet (iPhone) or in a FullScreenCover (iPad). However when using SplitScreen mode on an iPad (and thus switching between .compact and .regular the View remains in the container it was originally displayed. How can I correctly update this when switching between sizes on-the-fly? struct ContentView: View {     @Environment(\.horizontalSizeClass) var horizontalSizeClass     var body: some View {         Group {             Text("hidden behind modal")         }         .modal(isPresented: .constant(true)) {             if horizontalSizeClass == .regular {                 Rectangle()                     .fill(Color.red)                     .edgesIgnoringSafeArea(.all)             } else {                 Rectangle()                     .fill(Color.blue)                     .edgesIgnoringSafeArea(.all)             }         }     } } struct Modal<ModalContent: View>: ViewModifier {     @Environment(\.horizontalSizeClass) var horizontalSizeClass     @Binding var isPresented: Bool     @ViewBuilder let modalContent: ModalContent     func body(content: Content) -> some View {         if horizontalSizeClass == .regular {             content                 .fullScreenCover(isPresented: $isPresented) {                     modalContent                         .overlay {                             Text("horizontalSizeClass: regular")                         }                 }         } else {             content                 .sheet(isPresented: $isPresented) {                     modalContent                         .overlay {                             Text("horizontalSizeClass: compact")                         }                 }         }     } } extension View {     public func modal<Content: View>(isPresented: Binding<Bool>, @ViewBuilder content: @escaping () -> Content) -> some View {         modifier(Modal(isPresented: isPresented, modalContent: content))     } }
1
0
589
Aug ’22
[UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone on iPad???
Hi, in an App I maintain we have a huge crash count at launch on the iPad. While I can't reproduce it, looking at the stack trace it seems [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone evaluates to true under some conditions on iPadOS 15. (the crash occurs in an UIViewController that is allocated only on the iPhone in one code location) Is there anything that can cause [UIDevice currentDevice] to return nil, e.g. blocking the main thread? Thanks!
2
0
1.2k
Aug ’22
iOS 16: toolbar and navigationView
Hi everyone, I am experiencing an issue with Toolbar and NavigationView on iOS 16. Here are two small views to explain my bug: struct ContentView: View {     var body: some View {         NavigationView {             VStack {                 NavigationLink(destination: OtherView()) {                     Text("Link to OtherView")                 }             }         }     } } struct OtherView: View {     var body: some View {         ScrollView {             Text("ScrollView")         }         .toolbar {             ToolbarItem(placement: .bottomBar) {                 Text("Great Toolbar")             }         }     } } The toolbar of OtherView is displayed but is empty: If I replace NavigationView with NavigationStack, it works well: However, I should use a NavigationView because my app is available on iOS 15. Would you know how to solve this? Thank you, regards
6
1
3.9k
Aug ’22
UIDocumentPickerViewController -> OneDrive/G-Drive -> NSFileCoordinator
Hey, I'm not sure I'm even in the correct ballpark - trying to allow my app to download largish videos from user's OneDrive and G-Drive to app Is it correct to use NSFileCoordinator in this way? How do I report progress as it downloads the video (is it possible?) Is it correct to dismiss the picker like this? anything else wrong (or, like is....any of it correct? :) it's sort of working with my contrived examples (I created new personal G-drive / Onedrive accounts, and copied vids up there), but...when I use a file from our corporate OneDrive, from shared folder, I get: "NSCocoaErrorDomain Code=3328 "The requested operation couldn’t be completed because the feature is not supported." Is this the NSFileProvider extension (Microsoft's) complaining? public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {     guard  let url = urls.first else {       return     }     let isSecurityScoped = url.startAccessingSecurityScopedResource()     print("(#function) - iSecurityScoped = (isSecurityScoped)")     print("(#function) - document at (url)")     let filename = String(UUID().uuidString.suffix(6)) + "_" +  url.lastPathComponent     let newURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(filename)          let readingIntent = NSFileAccessIntent.readingIntent(with: url, options: .withoutChanges)     fileCoordinator.coordinate(with: [readingIntent], queue: queue) { error in       defer {         if isSecurityScoped {           url.stopAccessingSecurityScopedResource()         }       }       if let error = error {         print("(#function) - (error)")         return       }       let safeURL = readingIntent.url       do {         let fileData = try Data(contentsOf: safeURL)         try fileData.write(to: newURL, options: .atomic)         print("(#function) - SUCCESS - newURL = (newURL)")       } catch {         print("(#function) - NOOOOO - (error)")       }     }     controller.dismiss(animated: true)   }
1
1
844
Aug ’22
iOS 16.0 beta 7 broke Text(Date(), style: .timer) in SwiftUI widgets
Hi, In my apps, the recent iOS 16.0 beta 7 (20A5356a) broke the .timer DateStyle property of the Text view, in a SwiftUI widget. In previous OS and beta, Text(Date(), style: .timer) was correctly displaying an increasing counter. In iOS 6.0 beta 7, Text(Date(), style: .timer) does not update anymore, (and is offset to the left). The other DateStyle (like .offset, .relative, ...) seems to update correctly. Anyone noticed that (very specific) problem ?
38
14
10k
Aug ’22
Wrong SF symbol displayed
Hi there! After a few months off, I'm starting a new app. I'm making a TabView like this: import SwiftUI struct ContentView: View {     @State private var tab: Tab = .adventures     var body: some View {         TabView(selection: $tab) {                         Text("Explore")                 .tag(Tab.explore)                 .tabItem {                     Label("Explore", systemImage: "airplane.circle")                 }             Text("Profile")                 .tag(Tab.profile)                 .tabItem {                     Label("Profile", systemImage: "person")                 }         }     }     enum Tab {         case explore, profile     } } As you noticed, I want airplane.circle and person SF Symbols on the TabView but SwiftUI is showing airplane.circle.fill and person.fill in the preview canvas and also when I run the app in the simulator. Why it is forcing me to show those icons? Xcode version: 13.4.1 SF Symbols version: 3.3 iOS deployment target: 15.0 Thank you.
2
0
1.2k
Sep ’22
ShareLink + FileRepresentation: Can't Save to Files
I'm having trouble getting the "Save to Files" option to work with ShareLink. Here's a simple example: struct Item: Transferable {     public static var transferRepresentation: some TransferRepresentation {         FileRepresentation(exportedContentType: .jpeg) { item in // Write a jpeg to disk             let url = URL.documentsDirectory.appending(path: "item.jpeg")             let jpegData = UIImage(named: "testImg")!.jpegData(compressionQuality: 1)!             try! jpegData.write(to: url)             return SentTransferredFile(url)         }     } } struct ContentView: View {     var body: some View {         ShareLink(item: Item(), preview: SharePreview("Test Item"))     } } The ShareSheet presents all of the usual options, but tapping "Save to Files" briefly presents an empty modal before immediately dismissing. The following errors are logged to the console: 2022-09-12 14:19:57.481592-0700 ExportTest[3468:1374472] [NSExtension] Extension request contains input items but the extension point does not specify a set of allowed payload classes. The extension point's NSExtensionContext subclass must implement `+_allowedItemPayloadClasses`. This must return the set of allowed NSExtensionItem payload classes. In future, this request will fail with an error. 2022-09-12 14:19:58.047009-0700 ExportTest[3468:1374472] [ShareSheet] cancelled request - error: The operation couldn’t be completed. Invalid argument Sharing finished with error: Error Domain=NSPOSIXErrorDomain Code=22 "Invalid argument" at SwiftUI/SharingActivityPickerBridge.swift:266 2022-09-12 14:19:58.584374-0700 ExportTest[3468:1379359] [AXRuntimeCommon] AX Lookup problem - errorCode:1100 error:Permission denied portName:'com.apple.iphone.axserver' PID:3472 ( 0   AXRuntime                           0x00000001ca77b024 _AXGetPortFromCache + 932 1   AXRuntime                           0x00000001ca77d1d8 AXUIElementPerformFencedActionWithValue + 772 2   UIKit                               0x00000002258b3284 3CB83860-AA42-3F9A-9B6E-2954BACE3DAC + 778884 3   libdispatch.dylib                   0x0000000105078598 _dispatch_call_block_and_release + 32 4   libdispatch.dylib                   0x000000010507a04c _dispatch_client_callout + 20 5   libdispatch.dylib                   0x00000001050820fc _dispatch_lane_serial_drain + 988 6   libdispatch.dylib                   0x0000000105082e24 _dispatch_lane_invoke + 420 7   libdispatch.dylib                   0x000000010508fcac _dispatch_workloop_worker_thread + 740 8   libsystem_pthread.dylib             0x00000001ed9e8df8 _pthread_wqthread + 288 9   libsystem_pthread.dylib             0x00000001ed9e8b98 start_wqthread + 8 ) Additionally, this error is logged when the ShareSheet is first presented (before tapping Save to Files): [ShareSheet] Couldn't load file URL for Collaboration Item Provider:<NSItemProvider: 0x282a1d650> {types = (     "public.jpeg" )} : (null) Has anybody had luck getting custom Transferable representations to work with ShareLink?
6
2
2.6k
Sep ’22
Xcode 14 try to build all SPM when building swiftUI preview
HI, I have an issue displaying SwiftUI previews with Xcode 14. My project has iOS and an watchOS Target. It also includes a lot of SPM, most of them only used by the PhoneApp. The project build successfully for both iOS and watchOS. I can see that when building the watch target, only SPM that are included in this target are build for for watchOS The issue is when I try to build a swiftUI preview of the watch target. In this case I can see on the build for Preview log that Xcode try to build ALL spm defined in the Xcode project, including the one that are not used by the watch Target, As a lot if spm are for iOS only, and doesn't build for watchOS, the build for preview fails, and I'm unable to preview my swiftUI views on the AppeWatch. Note that my project is working fine on Xcode 13. This issue is easy to reproduce in any Xcode projects containing a iOS and watchOS target by adding a SPM that is only for iOS. Any workaround to fix this issue ?
17
7
5.9k
Sep ’22
SwiftUI List with Selection is Highlighting even in non-edit mode
I recently updated my xcode and compiled my application developed in SwiftUI. The SwiftUI List started to behave different. List has Selection parameter for EditMode selection. However, now the list items are being selected and highlighted with grey highlighted color, even in a non-edit default mode. Ideally, it should only select the list item in edit mode. It is how it worked before. But now when the list item is tapped in non-edit mode, it is getting selected. Please, let me know how to make list with selection to highlight only in editmode. import SwiftUI struct ContentView: View {       struct Ocean: Identifiable, Hashable {     let name: String     let id = UUID()   }   private var oceans = [     Ocean(name: "Pacific"),     Ocean(name: "Atlantic")   ]       @State private var multiSelection = Set<UUID>()       var body: some View {           NavigationView {       VStack {                   List(oceans, selection: $multiSelection) { ocean in           Text(ocean.name)         }         .toolbar { EditButton() }       }       .padding()       .buttonStyle(PlainButtonStyle())     }   } }
5
1
3.7k
Sep ’22
SwiftUI 4 navigation bug on iOS 16?
Hi everyone, I am running into a navigation-related issue that appears to be new in iOS 16/SwiftUI 4. The code below illustrates the problem: struct ContentView: View {   @State private var input: String = ""   var body: some View {     NavigationStack {       VStack {         Spacer()         NavigationLink("Navigate") {           Text("Nested View")         }         Spacer()         TextEditor(text: $input)           .border(.red)           .frame(height: 40)       }       .padding()     }   } } The initial view consists of a navigation link and a text editor at the bottom of the screen. I run the app on an iPhone (or the simulator) in iOS 16 and click on the text editor at the bottom of the screen. This invokes the virtual keyboard, which pushes up the text field. Next, I click on "Navigate" to navigate to the nested view. I navigate immediately back, which brings back the initial view without the keyboard. Unfortunately, the text field isn't pushed back to the bottom and is now located in the middle of the screen. (see attached image) Did anyone experience similar issues? Is there a workaround I could use to force a re-layout of the initial view upon return from the navigation link? Thanks, Matthias
8
2
3.1k
Sep ’22
EditMode Example not working
I tried the example from https://developer.apple.com/documentation/swiftui/editmode. It's not working for me. struct ContentView: View { @Environment(\.editMode) private var editMode @State private var name = "Maria Ruiz" var body: some View { NavigationView { Form { Text(String(editMode!.wrappedValue.isEditing)) if editMode?.wrappedValue.isEditing == true { TextField("Name", text: $name) } else { Text("test") } } .animation(nil, value: editMode?.wrappedValue) .toolbar { // Assumes embedding this view in a NavigationView. EditButton() } } } } It shows the texts "false" and "test", before and after clicking Edit. What am I missing? I'm using XCode 14.0.1 and the deployment target is iOS 16. I also tried on a real iPhone and on iOS 15.5 in the Simulator. Thanks for any help.
3
1
1.8k
Sep ’22
Hyperlinks open in Web browser instead of embedded WKWebView using Swift5/SwiftUI
Good morning! I am developing an iOS app that gets its data from an API and displays it in a list. The list item view has NavigationLink embedded in it that sends users to a detail view. In this detail view, I have some Text views but the issue I am running into is a WKWebView that I have implemented to display some HTML that's is retrieved from the API call. The WKWebView displays the HTML just how I want it to. The issue I have is in the HyperLinks that are displayed in the WKWebView. When a user taps on a link, it opens inside of the web view. Instead of opening in the web view, I would like this link to open in the user's default web browser. I have searched and found ways of doing this in older versions of Swift using classes but my web view is initialized inside of a struct that conforms to the UIViewRepresentable protocol. I don't know how to get links to open in the browser instead of the WebView so any help would be appreciated. Here is the code for my WebView that is being used on the details page. struct NewsItemWebView: UIViewRepresentable { // HTML from API Call     var text: String // Method to create the View     func makeUIView(context: Context) -> WKWebView {         return WKWebView()     } // Method to update the View by changing properties of the WebView     func updateUIView(_ uiView: WKWebView, context: Context) {         uiView.isOpaque = false         uiView.backgroundColor = UIColor.white         uiView.loadHTMLString(text, baseURL: nil)     } } Here is how I am implementing the WebView on DetailView NewsItemWebView(text: item.PageContent) .frame(height: 450) Any help on how I can make links open in a browser would be great. Thanks in advance.
3
1
7.3k
Oct ’22
How to implement multiple selection types in NavigationSplitView?
In the sidebar column of the NavigationSplitView I'd like to have several sections. All the items are fetched with Core Data. View all photos (Photos entity in Core Data) Folder (Folder entity in Core Data) Folder A Folder B Folder C Tags (Tag entity in Core Data) Cat Dog In the content view, I'd like show the items based on the selection in the sidebar. I tried the following with some success but I think there should be another way of doing this. NavigationSplitView() { List(selection: $navigationModel.selectedCategory, content: { NavigationLink(value: Category(type: .all, predicate: NSPredicate(value: true), title: "View all items") ) {                     Text("View all items")                 }   Section { ForEach(folders){ folder in NavigationLink(value: Category(type: .folder, predicate: NSPredicate(format: "folder == %@", folder), title: folder.name) ) { FolderRow(folder: folder) // ... and so on. Another section for tags And in the content: ZStack{ List(selection: $navigationModel.selectedPhoto) {     ContentView(photos: FetchRequest(                   sortDescriptors: [sortDescriptor], predicate: navigationModel.selectedCategory?.predicate,                   animation: .default) //.... How can refractor this code with a better solution? The problem that I'm encountering is that the selection argument in the List accepts only one type of object. But I want to select more that one type of object. Another issue is that this solution won't conform to Codable if I'm thinking correctly and reseting the app state on the next launch would be cumbersome.
2
0
791
Oct ’22