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

Missing EnvironmentObject from TableColumn on macOS
I encountered a strange behavior that reminded me of when .sheet() modifiers didn't inherit environment objects. Unless I'm missing something very obvious, it seems to me that TableColumn may expose the same issue. At least on macOS, because the very same code does not crash on iOS. I'm posting this here before reporting a SwiftUI bug. Below is a gist for a playground: https://gist.github.com/keeshux/4a963cdebb1b577b87b08660ce9d3364 I also observe inconsistent behavior when building with Xcode 16.1 or 15.4, specifically: https://github.com/passepartoutvpn/passepartout/issues/872#issuecomment-2477687967 The workaround I resorted to is re-propagating the environment from the parent: https://github.com/passepartoutvpn/passepartout/pull/873/files#diff-c662c4607f2adfd0d4e2c2a225e0351ba9c21dbdd5fc68f23bc1ce28a20bce4dR45
1
0
119
5d
How to break `while` loop and `deliver partial result to `View`?
I make some small program to make dots. Many of them. I have a Generator which generates dots in a loop: //reprat until all dots in frame while !newDots.isEmpty { virginDots = [] for newDot in newDots { autoreleasepool{ virginDots.append( contentsOf: newDot.addDots(in: size, allDots: &result, inSomeWay)) } newDots = virginDots } counter += 1 print ("\(result.count) dots in \(counter) grnerations") } Sometimes this loop needs hours/days to finish (depend of inSomeWay settings), so it would be very nice to send partial result to a View, and/or if result is not satisfying — break this loop and start over. My understanding of Tasks and Concurrency became worse each time I try to understand it, maybe it's my age, maybe language barier. For now, Button with {Task {...}} action doesn't removed Rainbow Wheel from my screen. Killing an app is wrong because killing is wrong. How to deal with it?
4
0
148
2d
NSPersistentCloudKitContainer not saving 50% of the time
I'm using NSPersistentCloudKitContainer to save, edit, and delete items, but it only works half of the time. When I delete an item and terminate the app and repoen, sometimes the item is still there and sometimes it isn't. The operations are simple enough: moc.delete(thing) try? moc.save() Here is my DataController. I'm happy to provide more info as needed class DataController: ObservableObject { let container: NSPersistentCloudKitContainer @Published var moc: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "AppName") container.loadPersistentStores { description, error in if let error = error { print("Core Data failed to load: \(error.localizedDescription)") } } #if DEBUG do { try container.initializeCloudKitSchema(options: []) } catch { print("Error initializing CloudKit schema: \(error.localizedDescription)") } #endif moc = container.viewContext } }
1
0
99
1w
Background Tasks runs foreground
Hello everyone! I'm having a problem with background tasks running in the foreground. When a user enters the app, a background task is triggered. I've written some code to check if the app is in the foreground and to prevent the task from running, but it doesn't always work. Sometimes the task runs in the background as expected, but other times it runs in the foreground, as I mentioned earlier. Could it be that I'm doing something wrong? Any suggestions would be appreciated. here is code: class BackgroundTaskService { @Environment(\.scenePhase) var scenePhase static let shared = BackgroundTaskService() private init() {} // MARK: - create task func createCheckTask() { let identifier = TaskIdentifier.check BGTaskScheduler.shared.getPendingTaskRequests { requests in if requests.contains(where: { $0.identifier == identifier.rawValue }) { return } self.createByInterval(identifier: identifier.rawValue, interval: identifier.interval) } } private func createByInterval(identifier: String, interval: TimeInterval) { let request = BGProcessingTaskRequest(identifier: identifier) request.earliestBeginDate = Date(timeIntervalSinceNow: interval) scheduleTask(request: request) } // MARK: submit task private func scheduleTask(request: BGProcessingTaskRequest) { do { try BGTaskScheduler.shared.submit(request) } catch { // some actions with error } } // MARK: background actions func checkTask(task: BGProcessingTask) { let today = Calendar.current.startOfDay(for: Date()) let lastExecutionDate = UserDefaults.standard.object(forKey: "lastCheckExecutionDate") as? Date ?? Date.distantPast let notRunnedToday = !Calendar.current.isDate(today, inSameDayAs: lastExecutionDate) guard notRunnedToday else { task.setTaskCompleted(success: true) createCheckTask() return } if scenePhase == .background { TaskActionStore.shared.getAction(for: task.identifier)?() } task.setTaskCompleted(success: true) UserDefaults.standard.set(today, forKey: "lastCheckExecutionDate") createCheckTask() } } And in AppDelegate: BGTaskScheduler.shared.register(forTaskWithIdentifier: "check", using: nil) { task in guard let task = task as? BGProcessingTask else { return } BackgroundTaskService.shared.checkNodeTask(task: task) } BackgroundTaskService.shared.createCheckTask()
1
0
110
6d
How to draw emojis like the Lock Screen customisation?
On iOS you can create a new Lock Screen that contains a bunch of emoji, and they'll get put on the screen in a repeating pattern, like this: When you have two or more emoji they're placed in alternating patterns, like this: How do I write something like that? I need to handle up to three emoji, and I need the canvas as large as the device's screen, and it needs to be saved as an image. Thanks! (I've already written an emojiToImage() extension on String, but it just plonks one massive emoji in the middle of an image, so I'm doing something wrong there.)
0
0
113
1w
AttributeGraph: AG::Graph::update_main_refs(AG::AttributeID)
Hello, I recently have crashes on my application, it results in many crashes with different reasons, here are the different main reasons: AttributeGraph: AG::Graph::update_main_refs(AG::AttributeID) SwiftUICore: closure #1 in ViewLayoutEngine.explicitAlignment(_:at:) SwiftUICore: __swift_instantiateGenericMetadata My main problem is that these crashes appeared without any major changes to my app, and they never happen when I emulate the app from xcode whether on a simulator or a real device. I have other crashes with other errors I can provide them if necessary. So I have a lot of trouble identifying where the errors come from, I tried to activate zombie objects, and address sanitizer without it revealing anything. Thanks in advance for the answers.
0
0
133
1w
iOS 18.1 crash UIHostingView.layoutSubviews() / swift_unknownObjectWeakAssign / objc_storeWeak
We're seeing sporadic crashes on devices running iOS 18.1 - both beta and release builds (22B83). The stack trace is always identical, a snippet of it below. As you can tell from the trace, it's happening in places we embed SwiftUI into UIKit via UIHostingController. Anyone else seeing this? 4 libobjc.A.dylib 0xbe2c _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30 5 libobjc.A.dylib 0xb040 weak_register_no_lock + 396 6 libobjc.A.dylib 0xac50 objc_storeWeak + 472 7 libswiftCore.dylib 0x43ac34 swift_unknownObjectWeakAssign + 24 8 SwiftUI 0xeb74c8 _UIHostingView.base.getter + 160 9 SwiftUI 0x92124 _UIHostingView.layoutSubviews() + 112 10 SwiftUI 0x47860 @objc _UIHostingView.layoutSubviews() + 36
3
0
148
1w
Run identical UI/Unit tests on different build targets
I have different versions of my iOS App (written in SwiftUI). The app on the store, the App Clip, and one or two next version apps not yet released (e.g. A/B comparison). All good. But now I've started creating UI and Unit tests and I'm confused about how to get this working. Each build target has its own scheme. And in that scheme I have a Test plan for that target. E.g. The App Clip scheme has an App Clip test plan. Since all the app variants are very similar, I only have one set of unit tests and one set of UI tests so each test plan includes the same unit test target and the UI test target. Problem: When I selected a scheme (e.g. for the App Clip) and ran the tests, it turned out that all the tests ran for another build target, not the target of the scheme. I think this might be because within the definition of the test target there's a field specifying the host application. I.e. the build target. Question: How can I set up my project so that the test plan uses the relevant target build? Or do I have to duplicate all the test targets (one for each target)? Or do I have to manually change each test target before running it for a particular build target?
1
0
115
5d
refreshed/updated data on widgets
Hello, I have a small lightweight macOS application that includes a medium widget but the widget does not update with new data as often as I'd like. I understand that in apple's WidgetKit documentation they mention that apple controls when the widget updates due to battery life concerns, but I'd like to know if theres any way at all to control when the widget updates or when I think it makes sense to do so if I am not able to control how often it refreshes new data. https://github.com/Alexx1105/MacStat-v2.1
2
0
147
1w
macOS SwiftUI document app always shows file picker on startup
DESCRIPTION OF PROBLEM When my Document-based macOS SwiftUI app starts up, it always presents a document picker. I would like it to open any documents that were open when the app last quit, and if none were open, open an "Untitled" document. I understand that there is a setting in System Settings-> Desktop & Dock ("Close windows when quitting an application") that will cause windows to reopen when it is turned off, but I'd like to give users a chance to opt-in for reopening docs even when that is turned on, since it is difficult to find, on by default, and might not be the desired behavior for all apps. I don't see any way to get a list of currently open documents to persist them at shutdown. And even if that's considered a bad idea, I'd at least like a way to prevent the Document picker from being shown at startup and instead create an Untitled document if no documents were open. Ideally, I'd like a way to provide this functionality in SwiftUI that doesn't require macOS 15 or later STEPS TO REPRODUCE Create a SwiftUI macOS document application in Xcode using the provided template, Give it any name you want Run it, create a new ".exampletext" document, save it. Quit the app with the document open. Re-run the app, document picker is shown. Cancel the document picker and quit the app with no windows shown. Re-run the app, document picker is shown.
0
0
132
1w
My App crashes run-time occasionally when I use AVFoundation and related code
I am developing an app for Vehicle owners with a built-in map navigation feature with voice navigation support. The app works fine without voice navigation but when I use voice navigation it occasionally crashes and it crashes while voice navigation is not in progress. What makes it impossible to diagnose is that even though it crashed 10 times on the flight, I don't see any crash reports in 'Apple Connect'. I tried running it in a simulator and it didn't crash there! but on a real device, when I drive with the app navigating me I crashes abruptly after a few minutes and it's not while the voice navigation is speaking! I also ran the app without AVFoundation and it did not crash then. So I am 100% sure it is something with this AVFoundation framework. If anyone can help find the problem in my following code it would be really helpful. import SwiftUI import AVFoundation struct DirectionHeaderView: View { @Environment(\.colorScheme) var bgMode: ColorScheme var directionSign: String? var nextStepDistance: String var instruction: String @Binding var showDirectionsList: Bool @Binding var height: CGFloat @StateObject var locationDataManager: LocationDataManager @State private var synthesizer = AVSpeechSynthesizer() @State private var audioSession = AVAudioSession.sharedInstance() @State private var lastInstruction: String = "" @State private var utteranceDistance: String = "" @State private var isStepExited = false @State private var range = 20.0 var body: some View { VStack { HStack { VStack { if let directionSign = directionSign { Image(systemName: directionSign) } if !instruction.contains("Re-calculating the route...") { Text("\(nextStepDistance)") .onChange(of: nextStepDistance) { let distance = getDistanceInNumber(distance: nextStepDistance) if distance <= range && !isStepExited { startVoiceNavigation(with: instruction) isStepExited = true } } } } Spacer() Text(instruction) .onAppear { isStepExited = false utteranceDistance = nextStepDistance range = nextStepRange(distance: utteranceDistance) startVoiceNavigation(with: "In \(utteranceDistance), \(instruction)") } .onChange(of: instruction) { isStepExited = false utteranceDistance = nextStepDistance range = nextStepRange(distance: utteranceDistance) startVoiceNavigation(with: "In \(utteranceDistance), \(instruction)") } .padding(10) Spacer() } } .padding(.horizontal,10) .background(bgMode == .dark ? Color.black.gradient : Color.white.gradient) } func startVoiceNavigation(with utterance: String) { if instruction.isEmpty || utterance.isEmpty { return } if instruction.contains("Re-calculating the route...") { synthesizer.stopSpeaking(at: AVSpeechBoundary.immediate) return } let thisUttarance = AVSpeechUtterance(string: utterance) lastInstruction = instruction if audioSession.category == .playback && audioSession.categoryOptions == .mixWithOthers { DispatchQueue.main.async { synthesizer.speak(thisUttarance) } } else { setupAudioSession() DispatchQueue.main.async { synthesizer.speak(thisUttarance) } } } func setupAudioSession() { do { try audioSession.setCategory(AVAudioSession.Category.playback, options: AVAudioSession.CategoryOptions.mixWithOthers) try audioSession.setActive(true) } catch { print("error:\(error.localizedDescription)") } } func nextStepRange(distance: String) -> Double { var thisStepDistance = getDistanceInNumber(distance: distance) if thisStepDistance != 0 { switch thisStepDistance { case 0...200: if locationDataManager.speed >= 90 { return thisStepDistance/1.5 } else { return thisStepDistance/2 } case 201...300: if locationDataManager.speed >= 90 { return 120 } else { return 100 } case 301...500: if locationDataManager.speed >= 90 { return 150 } else { return 125 } case 501...1000: if locationDataManager.speed >= 90 { return 250 } else { return 200 } case 1001...10000: if locationDataManager.speed >= 90 { return 250 } else { return 200 } default: if locationDataManager.speed >= 90 { return 250 } else { return 200 } } } return 200 } func getDistanceInNumber(distance: String) -> Double { var thisStepDistance = 0.0 if distance.contains("km") { let stepDistanceSplits = distance.split(separator: " ") let stepDistanceText = String(stepDistanceSplits[0]) if let dist = Double(stepDistanceText) { thisStepDistance = dist * 1000 } } else { var stepDistanceSplits = distance.split(separator: " ") var stepDistanceText = String(stepDistanceSplits[0]) if let dist = Double(stepDistanceText) { thisStepDistance = dist } } return thisStepDistance } } #Preview { DirectionHeaderView(directionSign: "", nextStepDistance: "", instruction: "", showDirectionsList: .constant(false), height: .constant(0), locationDataManager: LocationDataManager()) }
2
0
134
1w
SwiftData Master Details
I want to create master details relationship between patient and vitals signs so which of option codes below are better performance wise ? Option one is master - details done manually .. option 1 @Model class TestResult { @Attribute(.primaryKey) var id: UUID var patientID: UUID Option 2 @Model final class Vital { var patient: Patient?
0
0
100
1w
custom EnvironmentKey lookup causes compiler error
I receive the following compiler error: Cannot infer key path from context; consider explicitly specifying a root type when I attempt an @Environment(\.foodRepository) lookup in a descendant View. Here's the setup in my App class: import SwiftUI import SwiftData @main struct BulkCutApp: App { private var foodRepository: FoodRepository = /* some code*/ var body: some Scene { WindowGroup { ContentView() .foodRepository(foodRepository) } } } extension View { func foodRepository(_ customValue: FoodRepository) -> some View { environment(\.foodRepository, customValue) } } extension EnvironmentValues { var foodRepository: FoodRepository { get { self[FoodRepositoryKey.self] } set { self[FoodRepositoryKey.self] = newValue } } } struct FoodRepositoryKey: EnvironmentKey { static var defaultValue: FoodRepository = FoodRepository(food:[]) } Nothing special in FoodRepository: @Observable class FoodRepository { var food: [Food] // more code }
0
0
72
1w
SwiftUI not observing SwiftData changes
I have an app with the following model: @Model class TaskList { @Attribute(.unique) var name: String // Relationships var parentList: TaskList? @Relationship(deleteRule: .cascade, inverse: \TaskList.parentList) var taskLists: [TaskList]? init(name: String, parentTaskList: TaskList? = nil) { self.name = name self.parentList = parentTaskList self.taskLists = [] } } If I run the following test, I get the expected results - Parent has it's taskLists array updated to include the Child list created. I don't explicitly add the child to the parent array - the parentList relationship property on the child causes SwiftData to automatically perform the append into the parent array: @Test("TaskList with children with independent saves are in the database") func test_savingRootTaskIndependentOfChildren_SavesAllTaskLists() async throws { let modelContext = TestHelperUtility.createModelContext(useInMemory: false) let parentList = TaskList(name: "Parent") modelContext.insert(parentList) try modelContext.save() let childList = TaskList(name: "Child") childList.parentList = parentList modelContext.insert(childList) try modelContext.save() let fetchedResults = try modelContext.fetch(FetchDescriptor<TaskList>()) let fetchedParent = fetchedResults.first(where: { $0.name == "Parent"}) let fetchedChild = fetchedResults.first(where: { $0.name == "Child" }) #expect(fetchedResults.count == 2) #expect(fetchedParent?.taskLists.count == 1) #expect(fetchedChild?.parentList?.name == "Parent") #expect(fetchedChild?.parentList?.taskLists.count == 1) } I have a subsequent test that deletes the child and shows the parent array being updated accordingly. With this context in mind, I'm not seeing these relationship updates being observed within SwiftUI. This is an app that reproduces the issue. In this example, I am trying to move "Finance" from under the "Work" parent and into the "Home" list. I have a List that loops through a @Query var taskList: [TaskList] array. It creates a series of children views and passes the current TaskList element down into the view as a binding. When I perform the operation below the "Finance" element is removed from the "Work" item's taskLists array automatically and the view updates to show the removal within the List. In addition to that, the "Home" item also shows "Finance" within it's taskLists array - showing me that SwiftData is acting how it is supposed to - removed the record from one array and added it to the other. The View does not reflect this however. While the view does update and show "Finance" being removed from the "Work" list, it does not show the item being added to the "Home" list. If I kill the app and relaunch I can then see the "Finance" list within the "Home" list. From looking at the data in the debugger and in the database, I've confirmed that SwiftData is working as intended. SwiftUI however does not seem to observe the change. ToolbarItem { Button("Save") { list.name = viewModel.name list.parentList = viewModel.parentTaskList try! modelContext.save() dismiss() } } To troubleshoot this, I modified the above code so that I explicitly add the "Finance" list to the "Home" items taskLists array. ToolbarItem { Button("Save") { list.name = viewModel.name list.parentList = viewModel.parentTaskList if let newParent = viewModel.parentTaskList { // MARK: Bug - This resolves relationship not being reflected in the View newParent.taskLists?.append(list) } try! modelContext.save() dismiss() } } Why does my explicit append call solve for this? My original approach (not manually updating the arrays) works fine in every unit/integration test I run but I can't get SwiftUI to observe the array changes. Even more strange is that when I look at viewModel.parentTaskList.taskLists in this context, I can see that the list item already exists in it. So my code effectively tries to add it a second time, which SwiftData is smart enough to prevent from happening. When I do this though, SwiftUI observes a change in the array and the UI reflects the desired state. In addition to this, if I replace my custom list rows with an OutlineGroup this issue doesn't manifest itself. SwiftUI stays updated to match SwiftData when I remove my explicit array addition. I don't understand why my views, which is passing the TaskList all the way down the stack via Bindable is not updating while an OutlineGroup does. I have a complete reproducible ContentView file that demonstrates this as a Gist. I tried to provide the source here but it was to much for the post. One other anecdote. When I navigate to the TaskListEditorScreen and open the TaskListPickerScreen I get the following series of errors: error: the replacement path doesn't exist: "/var/folders/07/3px_03md30v9n105yh3rqzvw0000gn/T/swift-generated-sources/@_swiftmacro_09SwiftDataA22UIChangeDetectionIssue20TaskListPickerScreenV9taskLists33_A40669FFFCF66BB4EEA5302BB5ED59CELL5QueryfMa.swift" I saw another post regarding these and I'm wondering if my issue is related to this. So my question is, do I need to handle observation of SwiftData models containing arrays differently in my custom views? Why do bindings not observe changes made by SwiftData but they observe changes made explicitly by me?
1
0
161
5h
Get SwiftUI Image Data
I’m looking for the easiest and most efficient way to convert a SwiftUI Image to Data so that I can store it in SwiftData. let image: Image let data: Data = GetImageData(image: image) How would I implement the GetImageData function above? I have found examples of how to do so with UIImage but not Image.
1
0
152
1w
Async/Await and updating state
When using conformance to ObservableObject and then doing async work in a Task, you will get a warning courtesy of Combine if you then update an @Published or @State var from anywhere but the main thread. However, if you are using @Observable there is no such warning. Also, Thread.current is unavailable in asynchronous contexts, so says the warning. And I have read that in a sense you simply aren't concerned with what thread an async task is on. So for me, that begs a question. Is the lack of a warning, which when using Combine is rather important as ignoring it could lead to crashes, a pretty major bug that Apple seemingly should have addressed long ago? Or is it just not an issue to update state from another thread, because Xcode is doing that work for us behind the scenes too, just as it manages what thread the async task is running on when we don't specify? I see a lot of posts about this from around the initial release of Async/Await talking about using await MainActor.run {} at the point the state variable is updated, usually also complaining about the lack of a warning. But ow years later there is still no warning and I have to wonder if this is actually a non issue. On some ways similar to the fact that many of the early posts I have seen related to @Observable have examples of an @Observable ViewModel instantiated in the view as an @State variable, but in fact this is not needed as that is addressed behind the scenes for all properties of an @Observable type. At least, that is my understanding now, but I am learning Swift coming from a PowerShell background so I question my understanding a lot.
3
0
235
1w
No ObservableObject of Type "" found.
Im building an recipe app for the social media of my mother. i already have the functionality for the users, when a user gets created an empty array gets initiated at the database named favoriteRecipes, which stores the id of his favorite recipes to show in a view. This is my AuthViewModel which is relevant for the user stuff: import Firebase import FirebaseAuth import FirebaseFirestore protocol AuthenticationFormProtocol { var formIsValid: Bool { get } } @MainActor class AuthViewModel : ObservableObject { @Published var userSession: FirebaseAuth.User? @Published var currentUser: User? @Published var currentUserId: String? init() { self.userSession = Auth.auth().currentUser Task { await fetchUser() } } func signIn(withEmail email: String, password: String) async throws { do { let result = try await Auth.auth().signIn(withEmail: email, password: password) self.userSession = result.user await fetchUser() // fetch user sonst profileview blank } catch { print("DEBUG: Failed to log in with error \(error.localizedDescription)") } } func createUser(withEmail email: String, password: String, fullName: String) async throws { do { let result = try await Auth.auth().createUser(withEmail: email, password: password) self.userSession = result.user let user = User(id: result.user.uid, fullName: fullName, email: email) let encodedUser = try Firestore.Encoder().encode(user) try await Firestore.firestore().collection("users").document(result.user.uid).setData(encodedUser) await fetchUser() } catch { print("Debug: Failed to create user with error \(error.localizedDescription)") } } func signOut() { do { try Auth.auth().signOut() // sign out user on backend self.userSession = nil // wipe out user session and take back to login screen self.currentUser = nil // wipe out current user data model } catch { print("DEBUG: Failed to sign out with error \(error.localizedDescription)") } } func deleteAcocount() { let user = Auth.auth().currentUser user?.delete { error in if let error = error { print("DEBUG: Error deleting user: \(error.localizedDescription)") } else { self.userSession = nil self.currentUser = nil } } } func fetchUser() async { guard let uid = Auth.auth().currentUser?.uid else { return } currentUserId = uid let userRef = Firestore.firestore().collection("users").document(uid) do { let snapshot = try await userRef.getDocument() if snapshot.exists { self.currentUser = try? snapshot.data(as: User.self) print("DEBUG: current user is \(String(describing: self.currentUser))") } else { // Benutzer existiert nicht mehr in Firebase, daher setzen wir die userSession auf nil self.userSession = nil self.currentUser = nil } } catch { print("DEBUG: Fehler beim Laden des Benutzers: \(error.localizedDescription)") } } } This is the code to fetch the favorite recipes, i use the id of the user to access the collection and get the favoriteRecipes out of the array: import SwiftUI @MainActor class FavoriteRecipeViewModel: ObservableObject { @Published var favoriteRecipes: [Recipe] = [] @EnvironmentObject var viewModel: AuthViewModel private var db = Firestore.firestore() init() { Task { await fetchFavoriteRecipes() } } func fetchFavoriteRecipes() async{ let userRef = db.collection("users").document(viewModel.userSession?.uid ?? "") do { let snapshot = try await userRef.collection("favoriteRecipes").getDocuments() let favoriteIDs = snapshot.documents.map { $0.documentID } let favoriteRecipes = try await fetchRecipes(recipeIDs: favoriteIDs) } catch { print("DEBUG: Failed to load favorite recipes for user: \(error.localizedDescription)") } } func fetchRecipes(recipeIDs: [String]) async throws -&gt; [Recipe] { var recipes: [Recipe] = [] for id in recipeIDs { let snapshot = try await db.collection("recipes").document(id).getDocument() if let recipe = try? snapshot.data(as: Recipe.self) { recipes.append(recipe) } } return recipes } } Now the Problem occurs at the build of the project, i get the error SwiftUICore/EnvironmentObject.swift:92: Fatal error: No ObservableObject of type AuthViewModel found. A View.environmentObject(_:) for AuthViewModel may be missing as an ancestor of this view. I already passed the ViewModel instances as EnvironmentObject in the App Struct. import SwiftUI import FirebaseCore class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -&gt; Bool { FirebaseApp.configure() return true } } @main struct NimetAndSonApp: App { @StateObject var viewModel = AuthViewModel() @StateObject var recipeViewModel = RecipeViewModel() @StateObject var favoriteRecipeViewModel = FavoriteRecipeViewModel() @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { ContentView() .environmentObject(viewModel) .environmentObject(recipeViewModel) .environmentObject(favoriteRecipeViewModel) } } }
1
0
163
1w
Hide TabItems?
Is there really no way to hide a TabItem using the built-in TabView? I have 6 pages, but the 6th one I want hidden from the bottom tab bar, because I have a button that programmatically navigates to it on the navigation bar. I did not want to have to code a custom tab bar due to losing some useful features like pop to root in Navigation Stack.
0
0
118
1w