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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Why does my SwiftUI app crash when opened from an intent?
I'm encountering a crash in my SwiftUI app when it is opened via an AppIntent. The app runs perfectly when launched by tapping the app icon, but it crashes when opened from an intent. Here is a simplified version of my code: import AppIntents import SwiftData import SwiftUI @main struct GOGODemoApp: App { @State private var state: MyController = MyController() var body: some Scene { WindowGroup { MyView() //.environment(state) // ok } .environment(state) // failed to start app, crash with 'Dispatch queue: com.apple.main-thread' } } struct MyView: View { @Environment(MyController.self) var stateController var body: some View { Text("Hello") } } @Observable public class MyController { } struct OpenIntents: AppIntent { static var title: LocalizedStringResource = "OpenIntents" static var description = IntentDescription("Open App from intents.") static var openAppWhenRun: Bool = true @MainActor func perform() async throws -> some IntentResult { return .result() } } Observations: The app works fine when launched by tapping the app icon. The app crashes when opened via an AppIntent. The app works if I inject the environment in MyView instead of in WindowGroup. Question: Why does injecting the environment in WindowGroup cause the app to crash when opened from an intent, but works fine otherwise? What is the difference when injecting the environment directly in MyView?
0
0
64
3d
Drag and Drop using SwiftUI
Overview I am bit confused regarding drag and drop on SwiftUI I think there are 2 approaches but I am stuck with both approaches WWDC22 When using the new draggable, dropDestination, Transferable API, only single items are draggable. Multiple items in a list are not draggable. I have filed a feedback FB10128110 WWDC21 I have faced a couple of issues for drag and drop introduced in WWDC21 (onDrag, onDrop, itemIdentifier), the Feedback ids are FB9854301, FB9854569, FB9855245, FB9855532, FB9855567, FB9855575. It contains sample projects, would really appreciate if someone could have a look it. Note: All feedbacks include a sample project with detail steps and some even have screenshots and videos Questions: If my approach is wrong or if I am missing something? Unfortunately I didn't manage to get a SwiftUI lab session (got cancelled), so please help me with these issues.
4
1
2.7k
3d
Contents of Swift dictionaries and arrays being lost
Just when I think I am finally starting to understand Swift I come across a gotcha like the following: I have two object, a swiftui display and one of data to be displayed. Ok, sounds easy. The data is read out of a JSON file so I have a set of arrays and dictionaries. The data is valid when read, it is definitely there, but when I go to display it, its gone. Just vanished. Wasted about a day on this so far, and I’ve seen it before, the inability to pass out of an object an array or dictionary with contents intact. If I create an array var, and not let the system do it, contents are preserved. So, in the data object I’ll have something like this: struct DataObject{ var item: [String:Any] item=JSONData serialized out of memory, and may have say, 12 fields } In my SwiftUI module I have: var item=dataObject.item dataObject.item now has 0 fields. I can allocate and initialize a dictionary in DataObject and those elements come through fine. So it seems like the stuff being serialized from JSON is being deleted out from under me.
3
0
157
4d
SwiftData rollback not updating the UI
I'm building a simple App using SwiftData. In my app a user can create, remove and edit posts. When editing, I want them to be able to hit "Save" to persist the changes or "Cancel" to discard the changes. The approach I'm using is to disable autosave and call modelContext.save() when saving and modelContext.rollback() when discarding the changes. So my modelContainer is defined as follows: WindowGroup { ContentView() .modelContainer(for: [Post.self], isAutosaveEnabled: false) } and I Save and Cancel like this: PostForm(post: post) .toolbar { ToolbarItemGroup(placement: .cancellationAction) { Button("Cancel") { if modelContext.hasChanges { modelContext.rollback() } dismiss() } } ToolbarItemGroup(placement: .confirmationAction) { Button("Save") { do { if modelContext.hasChanges { try modelContext.save() } } catch { fatalError("Failed to save post: \(error.localizedDescription)") } callback?() dismiss() } } } The issue I am facing is that after calling modelContext.rollback() my Posts aren't updating in the UI, they still show the changes. Restarting the app shows the Posts without the changes so I'm guessing that modelContext.rollback() is in fact discarding the changes and not persisting them in the Storage, the UI is the one that is not reacting to the change. Am I doing something wrong here? Is this approach correct?
0
0
99
4d
Swiftui Custom Fonts not showing
Hello, My Custom fonts are not showing in SwiftUI. I am all up to date on all of my software and I have added my TTF's to a fonts folder in my collection. I also added the "Fonts provided by application" array type to my info.plist and the fonts as elements. Here is my code. I have no idea what I'm doing wrong. Is there a bug in the latest version of Swiftui? Text("Hello World") 			.font(.custom("VervelleScript-lgxR0", size: 36))
6
1
5.8k
4d
iPadOS 18 TabView / NavigationSplitView title
I have a TabView with individual tabs containing NavigationSplitViews. On iPadOS 18, when moving the new UI into a sidebar, the title of the first column in the current split view randomly spins its way in and out of view. Is this just a beta bug, or am I doing something wrong? Hard to convey without a recording, but hopefully the screenshots will show what I mean. Thanks.
1
0
74
4d
SwiftUI List misaligned with title bar.
Hello! I am making an app in SwiftUI and find it hard to make good-looking UIs with SwiftUI when using the List. When having a big navigation bar, the list appears misaligned with the title. This is a preview within Xcode. Don't know if that changes anything 🤷. Below is the code. I should note I am using Xcode 16 beta 3. // // SwiftUIView.swift // import SwiftUI struct SwiftUIView: View { struct D { var id: Int var name: String var identifier: String } let items: [(Int, D)] = [ (0, D(id: 0, name: "Test One", identifier: "one.example.test")), (1, D(id: 1, name: "Test One", identifier: "two.example.test")), (2, D(id: 2, name: "Test One", identifier: "three.example.test")), (3, D(id: 3, name: "Test One", identifier: "four.example.test")) ] var body: some View { NavigationStack { List(items, id: \.1.id) { idx, d in VStack(alignment: .leading) { Text(d.name) .bold() Text(d.identifier) } } .navigationTitle("Hello Title") } } } #Preview { SwiftUIView() }
2
0
146
4d
How to replace tabBar with bottomBar with smooth animation in SwiftUI?
I am trying to replace the navigation tab bar with a custom bottom toolbar when a view enters edit mode. Currently, I am using the following code to achieve this: content .toolbar(isEditing ? .hidden : .visible, for: .tabBar) . toolbar(isEditing ? .visible : .hidden, for: .bottomBar) However, this results in a janky animation. When the bottom bar appears, it animates in above (in contrast to in place of) the tab bar, then "jumps" back down to the correct offset without animation. I had to workaround this by delaying the appearance of bottom bar by 0.3s. I am already using withAnimation(). Is this a bug or am I using the APIs incorrectly? Is there a more seamless way to achieve this switching effect other than delaying the bottom bar? Thanks!
2
0
178
5d
Really High Energy Use
I'm developing an app where users can select items to add to a screen, similar to creating a Canva presentation or choosing blocks in Minecraft. However, I'm encountering an issue with energy usage. When users click the arrows to browse different items, the energy use spikes significantly. Although it returns to normal after a while, continuous clicking causes the energy use to skyrocket. The images I'm using are 500x500 pixels. Ideally, I would like to avoid caching all the images, as the app might have up to 500 items and caching them all would consume too much memory. I have tried numerous way to avoid this but I just can’t seem to make it work. Would anyone know how to avoid such problem? I have included a picture of the energy use when just opened, and one after like 10 seconds of continuously clicking on an arrow to see more items. Also a picture of how the app looks. struct ContentView: View { struct babyBackground { var littleImage = "" } @State var firstSet: [babyBackground] = [ babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), babyBackground(littleImage: "anotherShape"), babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), babyBackground(littleImage: "anotherShape") ] @State var secondSet: [babyBackground] = [ babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), babyBackground(littleImage: "anotherShape"), babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), babyBackground(littleImage: "anotherShape"), babyBackground(littleImage: "circle") ] @State var thirdSet: [babyBackground] = [ babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), ] let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 4) func createBackgroundGridView(for backgrounds: [babyBackground], columns: [GridItem] ) -> some View { LazyVGrid(columns: columns, spacing: 10) { ForEach(0..<backgrounds.count, id: \.self) { index in Button(action: { }, label: { if let path = Bundle.main.path(forResource: backgrounds[index].littleImage, ofType: "png"), let uiImage = UIImage(contentsOfFile: path) { Image(uiImage: uiImage) .resizable() .frame(width: 126, height: 96) } }) } } .padding() } @State var indexOn = 0 var body: some View { HStack{ Button(action: { indexOn = (indexOn == 0) ? 2 : indexOn - 1 }) { Label("", systemImage: "arrowtriangle.left.fill") .font(.system(size: 50)) } Spacer() ScrollView { switch indexOn { case 0: createBackgroundGridView(for: firstSet, columns: columns) case 1: createBackgroundGridView(for: secondSet, columns: columns) case 2: createBackgroundGridView(for: thirdSet, columns: columns) case 3: createBackgroundGridView(for: thirdSet, columns: columns) default: createBackgroundGridView(for: firstSet, columns: columns) } } .frame(maxWidth: .infinity, maxHeight: .infinity) Spacer() Button(action: { indexOn = (indexOn == 2) ? 0 : indexOn + 1 }) { Label("", systemImage: "arrowtriangle.right.fill") .font(.system(size: 50)) } } } } Energy Use when app starts: Energy use after clicking for about 10 seconds: App UI:
1
1
143
5d
Map behaves differently compared to MKMapView
Hey, I have a problem. I was using MKMapView in my app, and in the view where I had a background at the top of the screen, in the example it was Color.red, it extended all the way to the top of the screen. Now, I wanted to switch to the newer Map and I'm seeing an issue because I'm getting a navigation bar that cuts off my color as I indicated in the picture. Does anyone know why this is happening and if there's another way to achieve this? Steps to reproduce: Change MapView() to Map() to see difference import SwiftUI import MapKit @main struct TestAppApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { var body: some View { NavigationStack { ScrollView(.vertical) { Color.red .padding(.top, -200) .frame(height: 200) MapView().frame(minHeight: 300) // change this line to Map } .navigationTitle("Title") .navigationBarTitleDisplayMode(.large) } } } private typealias ViewControllerRepresentable = UIViewControllerRepresentable struct MapView: ViewControllerRepresentable { typealias ViewController = UIViewController class Controller: ViewController { var mapView: MKMapView { guard let tempView = view as? MKMapView else { fatalError("View could not be cast as MapView.") } return tempView } override func loadView() { let mapView = MKMapView() view = mapView } } func makeUIViewController(context: Context) -> Controller { Controller() } func updateUIViewController(_ controller: Controller, context: Context) { update(controller: controller) } func update(controller: Controller) { } } #Preview { ContentView() } I got: I want:
1
0
170
5d
Not receive onDisappear event on the first WindowGroup
Hi, I'm working on visionOS and find I can't get onDisappear event just on the first window after app launch. It comes like that: WindowGroup(id:"WindowA"){ MyView() .onDisappear(){ print("WindowA disappear") } } WindowGroup(id:"WindowB"){ MyView() .onDisappear(){ print("WindowB disappear") } } WindowGroup(id:"WindowC"){ MyView() .onDisappear(){ print("WindowC disappear") } } When the app first launch, it will open WindowA automatically And then I open WindowB and WindowC programatically. Then I tap the close button on window bar below window. If I close WindowB/WindowC, I can receive onDisappear event If I close WindowA, I can't receive onDisappear event If I reopen WindowA after it is closed and then close it again by tap the close button below window, I can receive onDisappear event Is there any logic difference for the first window on app launch? How can I get onDisappear Event for it. I'm using Xcode 16 beta 2
3
0
192
5d
SwiftData Model deletion works unstable
Hi, I believe this question belongs here instead of Stack Overflow as SwiftUI + SwiftData is too new. I am using Model Context from a static Helper class: Class Helper { static let shared = Helper() var modelContext: ModelContext? } call to insert data on the 1st screen: Helper.shared.modelContext?.insert(item) Query Model declaration on the 1st screen: @Query private var products: [ProductModel] also autoSave turned to false: .onAppear{ Helper.shared.modelContext?.autosaveEnabled = false } periodically update data via a standard Timer object: for item in products { item.price = 500 } SwiftData works just fine in this 1st screen, but when we try to delete the Model and move on to next screen, we found out memory of the previous screen Model (ProductModel) in this case is still persisted and keep increasing! Eventually causing hang in the 2nd screen. Model deletion code in onDisappear of the 1st screen: .onDisappear{ try? Helper.shared.modelContext?.delete(model: ProductModel.self) try? Helper.shared.modelContext?.save() } Any clue where we might be wrong? Thanks
1
0
120
5d
Text Above List w/ VStack Appears as View's Title
I am curious about the fact that the Text above the VStack is shown as a title to the view. I didn't know one could place Text above a VStack without another VStack. Here's the partial code showing the situation. @State private var results = [Result]() var body: some View { Text("Songs of Al Di Meola on iTunes") .font(.title3) .fontWeight(.bold) List(results, id: \.trackId) { item in VStack(alignment: .leading) { Text(item.trackName) .font(.headline) Text(item.collectionName) } } .task { await loadData() } } See picture for details.
0
0
85
5d
How Does Update Closure Work in RealityView
I have looked here: Reality View Documentation Found this thread: RealityView Update Closure Thread I am not able to find documentation on how the update closure works. I am loading attachments using reality view's attachment feature (really helpful). I want to remove them programmatically from another file. I found that @State variables can be used. But I am not able to modify them from out side of the ImmersiveView swift file. The second problem I faced was even if I update them inside the file. My debugging statements don't execute. So exactly when does update function run. I know it get's executed at the start (twice for some reason). It also get's executed when I add a window using: openWindow?(id: "ButtonView") I need to use the update closure because I am also not able to get the reference to RealityViewAttachment outside the RealityView struct. My Code(only shown the code necessary. there is other code): @State private var pleaseRefresh = "" @StateObject var model = HandTrackingViewModel() var body: some View { RealityView { content, attachments in if let immersiveContentEntity = try? await Entity(named: "Immersive", in: realityKitContentBundle) { content.add(immersiveContentEntity) } content.add(model.setupContentEntity()) content.add(entityDummy) print("View Loaded") } update: { content, attachments in print("Update Closure Executed") if (model.editWindowAdded) { print("WINDOW ADDED") let theattachment = attachments.entity(for: "sample")! entityDummy.addChild(theattachment) // more code here } } attachments: { Attachment(id: "sample") { Button(action: { model.canEditPos = true model.canRotate = false pleaseRefresh = "changed" }) { HStack { Image(systemName: "pencil.and.outline") .resizable() .scaledToFit() .frame(width: 32, height: 32) Text("Edit Placement") .font(.caption) } .padding(4) } .frame(width: 160, height: 60) } } How can the update method (or the code inside it) run when I want it to? I am new to swift. I apologize if my question seems naive.
1
0
155
5d
TabItem Not Respected In TabView
Hello, I'm a new programmer here, so this may be an error on my part, however I have tried my best to research the issue and believe I may have discover a bug. I have a set of tabItems inside of a TabView using a variable to track the selected tab called selectedIndex. I have added in a text view to watch the selected tab. This works correctly in the canvas and in a simulator, however whenever I build this on an iOS Device or for my Mac the selectedIndex does not change when selecting tabs like it does in the canvas and simulator. Instead it just stays at the default 0. Any assistance would be great. :-) import SwiftUI struct ContentView: View { @State private var selectedIndex = 0 var body: some View { Text("\(selectedIndex)") TabView(selection: $selectedIndex) { FilteredApplicantListView() .tabItem { Label("Applicant Processor", systemImage: "person.3.sequence.fill") } .tag(0) QuickFinancials() .tabItem { Label("Quick Financials", systemImage: "dollarsign.gauge.chart.leftthird.topthird.rightthird") } .tag(1) MoveInView() .tabItem { Label("Move Ins", systemImage: "figure.walk.arrival") } .tag(2) MoveOutView() .tabItem { Label("Move Outs", systemImage: "figure.walk.departure") } .tag(3) } } }
2
0
105
5d
Sheets no longer open when button is tapped while popover is visible
I have an extremely simple SwiftUI View with two buttons. One displays a sheet, the other one a popover. struct ContentView: View { @State private var showPopover = false @State private var showSheet = false var body: some View { VStack { Button("Popover") { showPopover = true } .popover(isPresented: $showPopover, content: { Text("Popover content") }) Spacer() Button("Sheet") { showSheet = true } } .padding() .sheet(isPresented: $showSheet) { Text("Lorem Ipsum") } } } On iPadOS, when the Popover is visible and the "Sheet" Button (that looks disabled but is not) is pressed, nothing happens and I get the following log: Attempt to present <TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView: 0x14508c600> on <TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier_: 0x14501fe00> (from <TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier_: 0x14501fe00>) which is already presenting <TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView: 0x140023e00>. What's even worse is, the "Sheet" Button is now in a broken state and no longer works at all. Is there a way to fix this or am I right in assuming this is a bug?
5
4
170
5d
iOS App shows blank screen after migrating to SwiftUI Lifecycle
This question was originally posted to StackOverflow, but I found it more suitable to be placed here. Was working on migrating one of my app from AppDelegate lifecycle to SwiftUI lifecycle according to this question. After following all the steps, The simulator simply shows a blank screen (the app does not launch at all): There is no log in the console. However, if the app is removed from the simulator (or device) and reinstalled, it will launch the new SwiftUI lifecycle correctly. So there seems to be some problem with scene caching that causes iOS to be confused after the migration. Am I missing something during the migration?
2
0
1.9k
5d
Migrating existing SwiftUI apps to the new multi platform template
I have an iOS 13 app that I’m hoping to release soon that is written entirely in SwiftUI. If I was starting from scratch today, I’d obviously use the new multi platform template which looks awesome.... But since I’m not starting from scratch, what are the recommendations/best practices for existing apps? Is there a path for migrating existing apps to take advantage of the new app structure (below) when moving to iOS 14? @main struct HelloWorld: App { var body: some Scene { WindowGroup { Text(“Hello, world!”).padding() } } }
2
0
1.5k
5d