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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Is it possible to get a swiftUI timer-text to align .trailing?
Please consider simple example below. I am trying to put a timer in the upper right corner of a live activity. I am done, it works, but I'm trying to get the timer to look better. If I take a regular text, I can get it to align properly by adjusting the .frame(), , but for a text with a timer inside it, alignment is ignored from what I can see. Text("Hello").frame(width: 90, alignment: .trailing).border(.red) /*Text(timerInterval: timeRange, countsDown: false) .monospacedDigit().font(.subheadline).frame(width: 90, alignment: .trailing).border(.red)*/ } Is there any way to fix this? Right now, I have a fixed width so that HH:mm:ss will fit, but that doesn't look super great if it's just minutes and seconds for example, there's an empty block to the right
1
0
139
2w
NavigationLink/Picker
I have a form container with a Navigation Stack at the top level. In a section I have a Navigation link followed by Picker(s) . On its own the navigation link works correctly but when a HStack with Text and Picker is added the navlink breaks . When the link is selected the picker list is presented. It seems others have had this issue which is usually solved by adding the NavigationStack , which is already at the top level. Any guidance is appreciated ( or work around - I added a section between the link and picker but that didn't help ) Joel
7
0
143
2w
Crash After Presenting SwiftUI Alert
I’m seeing a crash in production for a small percentage of users, and have narrowed it down based on logging to happening as or very shortly after an alert is presented using SwiftUI. This seems to be isolated to iOS 17.5.1, but since it’s a low-volume crash I can’t be sure there aren’t other affected versions. What can I understand from the crash report? Here’s a simplified version of the code which presents the alert, which seems so simple I can’t understand why it would crash. And following that is the crash trace. // View (simplified) @MainActor public struct MyView: View { @ObservedObject var model: MyViewModel public init(model: MyViewModel) { self.model = model } public var body: some View { myViewContent .overlay(clearAlert) } var clearAlert: some View { EmptyView().alert( "Are You Sure?", isPresented: $model.isClearAlertVisible, actions: { Button("Keep", role: .cancel) { model.clearAlertKeepButtonWasPressed() } Button("Delete", role: .destructive) { model.clearAlertDeleteButtonWasPressed() } }, message: { Text("This cannot be undone.") } ) } } // Model (simplified) @MainActor public final class MyViewModel: ObservableObject { @Published var isClearAlertVisible = false func clearButtonWasPressed() { isClearAlertVisible = true } func clearAlertKeepButtonWasPressed() { // No-op. } func clearAlertDeleteButtonWasPressed() { // Calls other code. } } Incident Identifier: 36D05FF3-C64E-4327-8589-D8951C8BAFC4 Distributor ID: com.apple.AppStore Hardware Model: iPhone13,2 Process: My App [379] Path: /private/var/containers/Bundle/Application/B589E780-96B2-4A5F-8FCD-8B34F2024595/My App.app/My App Identifier: com.me.MyApp Version: 1.0 (1) AppStoreTools: 15F31e AppVariant: 1:iPhone13,2:15 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: com.me.MyApp [583] Date/Time: 2024-06-21 20:09:20.9767 -0500 Launch Time: 2024-06-20 18:41:01.7542 -0500 OS Version: iPhone OS 17.5.1 (21F90) Release Type: User Baseband Version: 4.50.06 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x00000001a69998c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [379] Triggered by Thread: 0 Kernel Triage: VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter Thread 0 name: Thread 0 Crashed: 0 libswiftCore.dylib 0x00000001a69998c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 AttributeGraph 0x00000001d0cd61a4 Attribute.init<A>(body:value:flags:update:) + 352 (Attribute.swift:473) 2 SwiftUI 0x00000001ac034054 closure #1 in Attribute.init<A>(_:) + 128 (<compiler-generated>:0) 3 SwiftUI 0x00000001ac033cac partial apply for closure #1 in Attribute.init<A>(_:) + 32 (<compiler-generated>:0) 4 libswiftCore.dylib 0x00000001a6ad0450 withUnsafePointer<A, B>(to:_:) + 28 (LifetimeManager.swift:128) 5 SwiftUI 0x00000001ad624d14 closure #2 in UIKitDialogBridge.startTrackingUpdates(actions:) + 268 (UIKitDialogBridge.swift:370) 6 SwiftUI 0x00000001ad624ae0 UIKitDialogBridge.startTrackingUpdates(actions:) + 248 (UIKitDialogBridge.swift:369) 7 SwiftUI 0x00000001ad6250cc closure #4 in UIKitDialogBridge.showNewAlert(_:id:) + 72 (UIKitDialogBridge.swift:471) 8 SwiftUI 0x00000001abfdd050 thunk for @escaping @callee_guaranteed () -> () + 36 (:-1) 9 UIKitCore 0x00000001aa5722e4 -[UIPresentationController transitionDidFinish:] + 1096 (UIPresentationController.m:651) 10 UIKitCore 0x00000001aa571d88 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke.114 + 320 (UIPresentationController.m:1390) 11 UIKitCore 0x00000001aa5cb9ac -[_UIViewControllerTransitionContext completeTransition:] + 116 (UIViewControllerTransitioning.m:304) 12 UIKitCore 0x00000001aa34a91c __UIVIEW_IS_EXECUTING_ANIMATION_COMPLETION_BLOCK__ + 36 (UIView.m:16396) 13 UIKitCore 0x00000001aa34a800 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 624 (UIView.m:16429) 14 UIKitCore 0x00000001aa349518 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 436 (UIView.m:0) 15 UIKitCore 0x00000001aa356b14 -[UIViewAnimationState animationDidStop:finished:] + 192 (UIView.m:2400) 16 UIKitCore 0x00000001aa356b84 -[UIViewAnimationState animationDidStop:finished:] + 304 (UIView.m:2422) 17 QuartzCore 0x00000001a96f8c50 run_animation_callbacks(void*) + 132 (CALayer.mm:7714) 18 libdispatch.dylib 0x00000001aff61dd4 _dispatch_client_callout + 20 (object.m:576) 19 libdispatch.dylib 0x00000001aff705a4 _dispatch_main_queue_drain + 988 (queue.c:7898) 20 libdispatch.dylib 0x00000001aff701b8 _dispatch_main_queue_callback_4CF + 44 (queue.c:8058) 21 CoreFoundation 0x00000001a808f710 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1780) 22 CoreFoundation 0x00000001a808c914 __CFRunLoopRun + 1996 (CFRunLoop.c:3149) 23 CoreFoundation 0x00000001a808bcd8 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420) 24 GraphicsServices 0x00000001ecf3c1a8 GSEventRunModal + 164 (GSEvent.c:2196) 25 UIKitCore 0x00000001aa6c490c -[UIApplication _run] + 888 (UIApplication.m:3713) 26 UIKitCore 0x00000001aa7789d0 UIApplicationMain + 340 (UIApplication.m:5303) 27 SwiftUI 0x00000001ac27c148 closure #1 in KitRendererCommon(_:) + 168 (UIKitApp.swift:51) 28 SwiftUI 0x00000001ac228714 runApp<A>(_:) + 152 (UIKitApp.swift:14) 29 SwiftUI 0x00000001ac2344d0 static App.main() + 132 (App.swift:114) 30 My App 0x00000001001e7bfc static MyApp.$main() + 52 (MyApp.swift:0) 31 My App 0x00000001001e7bfc main + 64 32 dyld 0x00000001cb73de4c start + 2240 (dyldMain.cpp:1298)
2
0
210
3w
SwiftUI NavigationLink freezing when tapped
Any one getting any issues with NavigaitonLink to seemingly innocuous views freezing when tapped on? 1 CPU at 100% memory steadily increasing until app gets killed by the system. Will freeze if any NavigationLink on the view is tapped if certain views are linked to using NavigaitonLink. I note some people have been getting similar freezes if they use @AppStorage, but I'm not using @AppStorage. I do use CoreData tho. tho I have some views that use core data that don't freeze. https://developer.apple.com/forums/thread/708592?page=1#736374022 has anyone experienced similar issues? or know the cause. it doesn't seem to be any of my code because if I pause the debugger it stops on system code.
12
2
6.2k
Nov ’22
Can I preview "regular" view in widget extension?
Basically, in my widget/live activity, I want to extract reusable views into a separate file with an isolated view and preview. Dummy example below. I cannot do it because it says "missing previewcontext". The only way I've found is to add the view to my main app target, but I don't want to clutter my main app wiews that only exist in my widgets if I can avoid it. Can this be done somehow? Thoughts appreciated. Dummy example (tried with and without "previewLayout": struct StatusActivityView: View { let status: UserStatusData var body: some View { VStack(alignment: .center) { Text("Dummy example") }.background(.blue).padding(5) } } @available(iOS 16.2, *) struct StatusActivityView_Previews: PreviewProvider { static var previews: some View { let status = WidgetConstants.defaultEntry() return StatusActivityView(status: status).previewLayout(.sizeThatFits) } }
2
0
164
2w
SwiftUI document-based app bug
I have a simple text editor style app, based on the XCode template of an iOS document-based app. Everything works really – except the unfolding of the dropdown on the first opening of a new file. On real hardware (eg. my iPhone or iPad) it is consistently a problem. Everything is up-to-date and rebooted etc. etc. On the XCode Simulator, I can't get it to do it. I've included 3 screenshots, one showing how it should look when properly unfolded on the XCode Simulator, the other when it hasn't unfolded properly on the first opening of a document, and lastly, subsequent visits to that dropdown and it will behave correctly.
2
0
92
3w
SwiftUI onDrop not working with DropDelegate on iOS18
I am new to SwiftUI, and I wrote a ReorderableForEach struct with onDrag and onDrop, which is working well on iOS17. However it's not wokring on iOS18 beta1 or beta2 on my iPhone or simulator. When I long press the item, nothing happens. When I remove onDrop, I can perform a Drag animation, so I think something wrong with my onDrop code. the whole code: import UIKit import SwiftUI public typealias Reorderable = Identifiable & Equatable struct GridData: Identifiable, Equatable { let id: Int } public struct ReorderableForEach<Item: Reorderable, Content: View, Preview: View>: View { @Binding private var active: Item? @State private var hasChangedLocation = false private let items: [Item] private let content: (Item) -> Content private let preview: ((Item) -> Preview)? private let moveAction: (IndexSet, Int) -> Void private var onDropAction: ((Item) -> Void)? private var allowReorder: Bool public init( _ items: [Item], active: Binding<Item?>, allowReorder: Bool, @ViewBuilder content: @escaping (Item) -> Content, @ViewBuilder preview: @escaping (Item) -> Preview, moveAction: @escaping (IndexSet, Int) -> Void, onDropAction: ((Item) -> Void)? = nil ) { self.items = items self._active = active self.allowReorder = allowReorder self.content = content self.preview = preview self.moveAction = moveAction self.onDropAction = onDropAction } public init( _ items: [Item], active: Binding<Item?>, allowReorder: Bool, @ViewBuilder content: @escaping (Item) -> Content, moveAction: @escaping (IndexSet, Int) -> Void, onDropAction: ((Item) -> Void)? = nil ) where Preview == EmptyView { self.items = items self._active = active self.allowReorder = allowReorder self.content = content self.preview = nil self.moveAction = moveAction self.onDropAction = onDropAction } public var body: some View { ForEach(items) { item in if !allowReorder { contentView(for: item) } else if let preview { contentView(for: item) .onDrag { return dragData(for: item) } preview: { preview(item) } } else { contentView(for: item) .onDrag { return dragData(for: item) } } } } private func contentView(for item: Item) -> some View { content(item) .opacity(active == item && hasChangedLocation ? 0.5 : 1) .onDrop( of: [.text], delegate: ReorderableDragRelocateDelegate( item: item, items: items, active: $active, hasChangedLocation: $hasChangedLocation ) { from, to in withAnimation { moveAction(from, to) } } onDropAction: { item in onDropAction?(item) } ) } private func dragData(for item: Item) -> NSItemProvider { active = item return NSItemProvider(object: "\(item.id)" as NSString) } } struct ReorderableDragRelocateDelegate<Item: Reorderable>: DropDelegate { let item: Item var items: [Item] @Binding var active: Item? @Binding var hasChangedLocation: Bool var moveAction: (IndexSet, Int) -> Void var onDropAction: ((Item) -> Void)? func dropEntered(info: DropInfo) { guard item != active, let current = active else { return } guard let from = items.firstIndex(of: current) else { return } guard let to = items.firstIndex(of: item) else { return } hasChangedLocation = true if items[to] != current { moveAction(IndexSet(integer: from), to > from ? to + 1 : to) } } func dropUpdated(info: DropInfo) -> DropProposal? { DropProposal(operation: .move) } func performDrop(info: DropInfo) -> Bool { hasChangedLocation = false active = nil onDropAction?(item) return true } } struct ReorderableDropOutsideDelegate<Item: Reorderable>: DropDelegate { @Binding var active: Item? func dropUpdated(info: DropInfo) -> DropProposal? { DropProposal(operation: .move) } func performDrop(info: DropInfo) -> Bool { active = nil return true } } public extension View { func reorderableForEachContainer<Item: Reorderable>( active: Binding<Item?> ) -> some View { onDrop(of: [.text], delegate: ReorderableDropOutsideDelegate(active: active)) } } #Preview { ReorderableForEach( (1...10).map { GridData(id: $0) }, active: .constant(nil), allowReorder: true ) { item in Text("Item \(item.id)") .padding() .background(Color.blue) .cornerRadius(8) } preview: { item in Text("Preview \(item.id)") .padding() .background(Color.red) .cornerRadius(8) } moveAction: { from, to in print("Move from \(from) to \(to)") } } Am I missing something or this is a bug on iOS18? Thanks in advance.
1
2
145
3w
macOS SwiftUI Sheets are no longer resizable (Xcode 16 beta2)
For whatever reason SwiftUI sheets don't seem to be resizable anymore. The exact same code/project produces resizable Sheets in XCode 15.4 but unresizable ones with Swift included in Xcode 16 beta 2. Tried explicitly providing .fixedSize(horizontal false, vertical: false) everywhere humanly possible hoping for a fix but sheets are still stuck at an awkward size (turns out be the minWidth/minHeight if I provide in .frame).
4
1
177
2w
iOS DisclosureGroup content clipping
I have a SwiftUI page that I want to simplify by showing basic information by default, and putting the additional info behind a "Details" DisclosureGroup for advanced users. I started by laying out all the components and breaking things into individual Views. These all are laid out and look fine. Then I took several of them and added them inside a DisclosureGroupView. But all of a sudden, the views inside started getting crunched together and the contents of the DisclosureGroup got clipped about 2/3 of the way down the page. The problem I'm trying to solve is how to show everything inside the DIsclosureGroup. The top-level View looks like this: VStack { FirstItemView() SecondView() DetailView() // <- Shows disclosure arrow } Where DetailView is: struct DetailView: View { @State var isExpanded = true var body: some View { GeometryReader { geometry in DisclosureGroup("Details", isExpanded: $isExpanded) { ThirdRowView() Spacer() FourthRowView() VStack { FifthRowWithChartView() CaptionLabelView(label: "Third", iconName: "chart.bar.xaxis") } } } } } The FifthRowWithChartView is half-clipped. One thing that might contribute is that there is a Chart view at the bottom of this page. I've tried setting the width and height of the DisclosureGroup based on the height returned by the GeometryReader, but that didn't do anything. This is all on iOS 17.6, testing on an iPhone 15ProMax. Any tips or tricks are most appreciated.
2
0
180
2w
How to handle adding and removing items from NavigationSplitView
Hello, I'm new to app development and have a question that I have been searching all over the place to find an answer to. I have followed Apple's own guides and don't know how to move around the strange issue I am experiencing. I have a project using NavigationSplitView and have the code setup so that it navigates through an array of items. The two issues I am experiencing that I hope to find some help with are: I would like to be able to have my add button, instead of presenting a sheet, just navigate to a new item within the NavigationSplitView. This would be more natural for the type of data application I have created. At this time I create the item with a .sheet modifier and then the item is created and added to the array. However, I then have to tap on the newly created item to get it to be selected. Is this how SwiftUI should be working? Whenever an item is deleted from the list, and it was the last item selected or the last item in the array, the NavigationSplitView will continue showing that remaining item. The only way to get it to show an empty content screen is to force close the application and then reopen it. Since this is my first time posting, I'm not sure what information would be helpful, but would be happy to provide anything which could be of assistance. :-)
3
0
195
2w
@FocusState problem
Hi I have an enum of the TextFields in an Update SwiftData view. When the view opens, the focus is correct, and the button in the .toolbar keyboard sets the focus to nil and dismisses the keyboard. It works just fine. But, if I tap on a different TextField other than the original field that the focus was set in a .onAppear, the button on the keyboard dims out and no longer works. This same code works as expected in another view, the only difference in the Update view is that the data in the fields comes from an @Bindable variable. Any clue what is going on? Thanks so much! Blessings, --Mark
9
0
268
Jun ’24
Help, can't use TabView
Hi, I learned swift only a few weeks ago, and im trying to make a TabView in Xcode. But, it shows only one item! I've already made this work in other apps, but I can't get it working here! import SwiftUI struct tabs: View { var body: some View { TabView { ContentView() .tabItem { Image(systemName: "house.circle.fill") Text("Home") Settngs() .tabItem { Image(systemName:"gear.circle.fill") Text("Settings") } } } } } #Preview { tabs() } and also, I checked "settngs()" and its my name
1
0
165
2w
VisionOS NavigationStack background cannot be removed?
I have a simple example to demonstrate... struct MyView: View { var body: some View { Text("WOW") } } struct MyOtherView: View { var body: some View { NavigationStack { Text("WOW") } } } On VisionOS, MyOtherView has a glass background effect that cannot be disabled. glassBackgroundEffect(displayMode: .never) .background(.clear), .foregroundColor(.clear), none of them work. I then resorted to the SwiftUIIntrospect package to try set .clear on various child objects of the NavigationStack but nothing is working. I am in control of my own glass containers. I have a couple with space between them, but with the NavigationStack it sets a background behind both of them ruining the effect. This is what MyOtherView renders as: I'm looking for it to be completely transparent except the text. Like the below layout. For now I will have to roll my own navigation.
2
2
330
Apr ’24
Saving edited PDFs directly to application from QuickLook
I'm stuck on a problem where I need to be able to have the same editing capabilities as in .quickLookPreview and be able to save the edited file to the application with the "Done" button. So, in nutshell, I need to implement the same functionality many other applications provide including Apple's Files. However with .quickLookPreview I don't get the ability to save edited files directly to the application, and I've had no luck finding help from the internet (thus this question). Perhaps somebody has implemented this before and could give me a lead somewhere? PS. I'm trying to find a solution without any third party libraries
1
0
120
2w
SwiftData make my app very slow
Hello, I have been working on SwiftData since a month now and i found very weird that every time i update a data inside a SwiftData model my app became very slow. I used the instrument if something was wrong, and i see memory increasing without releasing. My app have a list with check and unchecked elements (screeshot below). I just press check and unchecked 15 times and my memory start from 149mb to 361mb (screenshots below). For the code i have this model. final class Milestone: Identifiable { // ********************************************************************* // MARK: - Properties @Transient var id = UUID() @Attribute(.unique) var uuid: UUID var text: String var goalId: UUID var isFinish: Bool var createdAt: Date var updatedAt: Date var goal: Goal? init(from todoTaskResponse: TodoTaskResponse) { self.uuid = todoTaskResponse.id self.text = todoTaskResponse.text self.goalId = todoTaskResponse.goalId self.isFinish = todoTaskResponse.isFinish self.createdAt = todoTaskResponse.createdAt self.updatedAt = todoTaskResponse.updatedAt } init(uuid: UUID, text: String, goalId: UUID, isFinish: Bool, createdAt: Date, updatedAt: Date, goal: Goal? = nil) { self.uuid = uuid self.text = text self.goalId = goalId self.isFinish = isFinish self.createdAt = createdAt self.updatedAt = updatedAt self.goal = goal } } For the list i have var milestonesView: some View { ForEach(milestones) { milestone in MilestoneRowView(task: milestone) { milestone.isFinish.toggle() } .listRowBackground(Color.backgroundComponent) } .onDelete(perform: deleteMilestone) } And this is the cell struct MilestoneRowView: View { // ********************************************************************* // MARK: - Properties var task: Milestone var action: () -> Void init(task: Milestone, action: @escaping () -> Void) { self.task = task self.action = action } var body: some View { Button { action() } label: { HStack(alignment: .center, spacing: 8) { Image(systemName: task.isFinish ? "checkmark.circle.fill" : "circle") .font(.title2) .padding(3) .contentShape(.rect) .foregroundStyle(task.isFinish ? .gray : .primary) .contentTransition(.symbolEffect(.replace)) Text(task.text) .strikethrough(task.isFinish) .foregroundStyle(task.isFinish ? .gray : .primary) } .foregroundStyle(Color.backgroundComponent) } .animation(.snappy, value: task.isFinish) } } Does someone have a idea? Thanks
1
0
424
Apr ’24