Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

SwiftUI Documentation

Posts under SwiftUI subtopic

Post

Replies

Boosts

Views

Activity

@FetchRequest predicate is ignored if the context changes
I have a simple SwiftUI application with CoreData and two views. One view displays all "Place" objects. You can create new places and you can show the details for the place. Inside the second view you can add "PlaceItem"s to a place. The problem is that, once a new "PlaceItem" is added to the viewContext, the @NSFetchRequest seems to forget about its additional predicates, which I set in onAppear. Then every place item is shown inside the details view. Once I update the predicate manually (the refresh button), only the items from the selected place are visible again. Any idea how this can be fixed? Here's the code for my two views: struct PlaceView: View { @FetchRequest(sortDescriptors: []) private var places: FetchedResults<Place> @Environment(\.managedObjectContext) private var viewContext var body: some View { NavigationView { List(places) { place in NavigationLink { PlaceItemsView(place: place) } label: { Text(place.name ?? "") } } } .toolbar { ToolbarItem(placement: .primaryAction) { Button { let place = Place(context: viewContext) place.name = NSUUID().uuidString try! viewContext.save() } label: { Label("Add", systemImage: "plus") } } } .navigationTitle("Places") } } struct PlaceItemsView: View { @ObservedObject var place: Place @FetchRequest(sortDescriptors: []) private var items: FetchedResults<PlaceItem> @Environment(\.managedObjectContext) private var viewContext func updatePredicate() { items.nsPredicate = NSPredicate(format: "place == %@", place) } var body: some View { NavigationView { List(items) { item in Text(item.name ?? ""); } } .onAppear(perform: updatePredicate) .toolbar { ToolbarItem(placement: .primaryAction) { Button { let item = PlaceItem(context: viewContext) item.place = place item.name = NSUUID().uuidString try! viewContext.save() } label: { Label("Add", systemImage: "plus") } } ToolbarItem(placement: .navigationBarLeading) { Button(action: updatePredicate) { Label("Refresh", systemImage: "arrow.clockwise") } } } .navigationTitle(place.name ?? "") } } struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext var body: some View { NavigationView { PlaceView() } } } Thanks!
2
0
873
Feb ’22
ARQuickLook controls not displaying in SwiftUI
Hi, I'm embedding the QLPreviewController in a UIViewControllerRepresentable. When I view .usdz models I don't see the AR/Object selector at the top, nor the sharing button. I have tried presenting modally with a .sheet modifier and had the same result. What do I need to do to get the controls? Thanks, code attached. Code Spiff
3
0
1.7k
Mar ’22
Textfield with too small hit area
Hello, It's impossible to manage hit area for textfield and it's already too small by default (detected with Accessibility Inspector). I'm tried to force with modifier "frame(minHeight: xxx)", the component change the height but the hit area is still in same size. Have to tips to fix this issue?
3
1
2.5k
Mar ’22
.commandsRemoved() does not work for the first scene.
.commandsRemoved() does not work for the Window and WindowGroup scenes if it’s the primary group (first one). Then I tried to add new menu using the code .commands {       CommandGroup(replacing: .newItem) {           Button("New Document") {               newDocument { TestDocument() }           }           .keyboardShortcut("n") } But app crashed with error " Expected subclass override" The test app is a document-based app, with a welcome window using the new Window scene.
1
0
995
Jun ’22
focusable modifier does not work on Ventura
It works on Monterey, but not work on Ventura. struct ContentView: View { @FocusState private var focus: FocusableElement? @FocusedValue(\.focusedElement) var focusElement var body: some View { VStack(spacing: 30) { HStack { GroupBox { Circle() .focusable() .focused($focus, equals: .circle) .focusedValue(\.focusedElement, .circle) .frame(width: 100, height: 100) .padding() Text(focus == .circle ? "Selected" : "Not selected") } .onTapGesture { focus = .circle } GroupBox { Rectangle() .focusable() .focused($focus, equals: .rectangle) .focusedValue(\.focusedElement, .rectangle) .frame(width: 100, height: 100) .padding() Text(focus == .rectangle ? "Selected" : "Not selected") } } .onTapGesture { focus = .rectangle } Text("Focused Element: \(focusElement?.rawValue ?? "None")") } .padding() .frame(width: 500, height: 300) } } enum FocusableElement: Equatable, Hashable { case rectangle case circle } enum Selection: String, Hashable { case none case rectangle case circle } extension FocusedValues { struct FocusedElement: FocusedValueKey { typealias Value = Selection } var focusedElement: FocusedElement.Value? { get { self[FocusedElement.self] } set { self[FocusedElement.self] = newValue } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
1
0
657
Jun ’22
Navigation: update multiple times per frame
After updating to NavigationStack with nested navigation links (with navigation links in a navigation destination), I see a lot of warnings in Xcode 14 beta: Update NavigationAuthority bound path tried to update multiple times per frame. Update NavigationAuthority possible destinations tried to update multiple times per frame. The app often freezes when navigated with a NavigationLink. Do others see these problems?
24
17
19k
Jun ’22
ToolbarItemGroup(placement: .keyboard) is not showed with Sheet
struct ContentView: View {   @State var isPresented = false   var body: some View {     Button {       isPresented.toggle()     } label: {       Text("Button")     }     .sheet(isPresented: $isPresented) {       SubView()     }   } } struct SubView: View {   @State var text = ""   var body: some View {     NavigationStack {       TextEditor(text: $text)         .toolbar {           ToolbarItemGroup(placement: .bottomBar) {             Button("Click") {             }           }           ToolbarItemGroup(placement: .keyboard) {             Button("Click") {             }           }         }     }   } }
10
3
4.9k
Jun ’22
Storyboard target in Beta
I am currently running Xcode Version 14.0 beta (14A5228q) creating a Multiplatform app. I wanted to include a LaunchScreen so added a Launch Screen Storyboard to my project. To the the app to see it I went under Target for my app, General, and under App Icons and Launch Screen I set the Launch Screen File to my storyboard. This works perfectly when I run the app on iOS; however, when I run it on macOS I get an error:Launch Screen.storyboard error build: iOS storyboards do not support target device type "Mac". I see there's no way to differentiate between macOS and iOS with the file and there's only one target. Does anyone know a way to make the storyboard only launch when running the iOS app (and iPadOS) and not be seen when running macOS? Thanks
2
0
1.8k
Jul ’22
Swift charts displaying wrong theme through UIHostingController
Hi there, I'm currently using UIHostingController to display swift charts in uikit. The problem im facing is that the UIHostingController isn't outputting the intended theme. When the simulator/phone is on dark mode the view is still in light mode. Iv'e tried to force the view to use dark mode with: .environment(\.colorScheme, .dark) But it doesn't seem to help. Here's how I implement the UIHostingController to my view: let controller = UIHostingController(rootView: StatVC()) controller.view.translatesAutoresizingMaksIntoConstraints = false addChild(controller) controller.didMove(toParent: self) view.addSubview(controller.view) where StatVC() is the swiftui view which contains the swift chart.
1
0
1.2k
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
5.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
79k
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 ?
39
14
11k
Aug ’22
Textfield not updating integer with optional value
I am trying to get integer input by using textfield. However, I noticed that if I changed the binding variable as optional with an initial value of null, the textfield would not work. I would like to keep it as null initially because I want the placeholder to show text before the input, and if the int variable starts with any valid value, the text would not be shown. Is there a way to fix things here? struct TextFieldNumberInputView: View {     @Binding var intVariable: Int?     @State var isEditing: Bool = false     @State var placeholderText: String     @State var number: Int = 0          var body: some View {         VStack(alignment: .leading, spacing: 2){             TextField(placeholderText, value: $number, formatter: NumberFormatter()){             }             .textFieldStyle(InputTextFieldStyle())             .keyboardType(.numberPad)             .onReceive(Just(number)) {_ in                 print("number pad being editing")                 if isEditing == false && intVariable != nil {                                         isEditing = true                     print("number is being edited")                 } else if isEditing == true && intVariable != nil{                     isEditing = false                 }             }                          Text(placeholderText)                 .font(.caption2)                 .foregroundColor(isEditing ? Color(.systemGray3):Color.clear)                 .padding(.horizontal)                 .padding(.horizontal, 12)                  }.onTapGesture {             print("number pad being tapped, intVariable \(intVariable), \(number)")                          if number != nil {                 print("checking number")                 UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)             }                      }     }      }
2
0
748
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?
7
2
3.6k
Sep ’22
A basic DocumentGroup App presents two back "<" buttons on the navigation bar.
Please has anyone found a workaround for duplicate back buttons appearing on the toolbar of a ContentView launched from a DocumentGroup? The problem occurs with Xcode 14.0 running a basic DocumentGroup App on iOS 16.0. To reproduce, simply build a new project using the "Document App" template. Build and run in the iOS/iPadOS simulator or on an iOS/iPadOS device. Two back buttons appear. Only one functions. I've not found a way to eliminate the dud. This problem has occurred throughout the Xcode 14.0 beta program.
8
6
1.9k
Sep ’22
Changing the live activity without push notification
I am trying to implement "Live activity" to my app. I am following the Apple docs. Link: https://developer.apple.com/documentation/activitykit/displaying-live-data-with-live-activities Example code: struct LockScreenLiveActivityView: View { let context: ActivityViewContext<PizzaDeliveryAttributes> var body: some View { VStack { Spacer() Text("\(context.state.driverName) is on their way with your pizza!") Spacer() HStack { Spacer() Label { Text("\(context.attributes.numberOfPizzas) Pizzas") } icon: { Image(systemName: "bag") .foregroundColor(.indigo) } .font(.title2) Spacer() Label { Text(timerInterval: context.state.deliveryTimer, countsDown: true) .multilineTextAlignment(.center) .frame(width: 50) .monospacedDigit() } icon: { Image(systemName: "timer") .foregroundColor(.indigo) } .font(.title2) Spacer() } Spacer() } .activitySystemActionForegroundColor(.indigo) .activityBackgroundTint(.cyan) } } Actually, the code is pretty straightforward. We can use the timerInterval for count-down animation. But when the timer ends, I want to update the Live Activity view. If the user re-opens the app, I can update it, but what happens if the user doesn't open the app? Is there a way to update the live activity without using push notifications?
11
9
6.2k
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
2.5k
Sep ’22