Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftUI Orientation Change
I have been struggling for nearly a week to handle orientation changes. In a previous post https://developer.apple.com/forums/thread/755957 I was strongly advised to use Size Classes, and I am trying to do that. by following this post: https://forums.developer.apple.com/forums/thread/126878) But I still can get it to work, so far I am just trying to initialize all the variables I will use later on. please bear with me I am 65 and have not done any coding for coming for 40 years. This my latest effort: import SwiftUI final class myOrientationChange: ObservableObject { @Published var myOrient: String = "" @Environment(\.verticalSizeClass) var myVertClass: UserInterfaceSizeClass? @Environment(\.horizontalSizeClass) var myHorizClass: UserInterfaceSizeClass? var _observer: NSObjectProtocol? if myHorizClass == .compact && myVertClass == .regular { self.myOrient = "Portrait" } elseif myHorizClass == .regular && myVertClass == .compact { self.myOrient = "Landscape" } else { self.myOrient = "Something Else" } } struct ContentView: View { @EnvironmentObject var envOrient: myOrientationChange var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") Text("Orientation is \(envOrient.myOrient)") } .padding() } } #Preview { ContentView() } I will go on to use the NotificationCenter to trap there change of orientation even. On the line if myHorizClass == ......... It tells me "Expected declaration in declaration of 'myOrientChange'" What have I done wrong?
1
0
266
May ’24
(Swift) TextField border contained in a view remains visible even when the view is fully overlapped by another view.
I have a ZStack that contains a VStack with 2 views (view1 and view2) and a third view (view3). So, is either that view1 and View1 are visible, or view3 is visible. This is the relevant code: ZStack { VStack { view1() View2() } if showView3 View3() } view1 and view2 are 400px in width and 200px in height, while view3 is 400 x 400 px, so that it completely overwrite view1/view2 when visible. The problem I'm trying to solve is that the border of a TextField placed in view1 is visible when showView3 is true, what should not be happening (possible glitch in swift?). To show the problem, I prepared a code sample, which shows that when view3 is active, it completely overwrites view1/view2, but still, the border of the TextField remains visible. (See screenshot below) struct TestZStackView: View { @State private var showView3 = false var body: some View { ZStack { VStack { Toggle("view3", isOn: $showView3) View1() .frame(width: 400, height: 200) .background(Color.red) .zIndex(1) View2() .frame(width: 400, height: 200) .background(Color.green) .zIndex(1) } if showView3 { View3() .frame(width: 400, height: 400) .background(Color.blue) .zIndex(2) } } } } struct View1: View { var body: some View { TextField("Enter text", text: .constant("")) .padding() .cornerRadius(5) .textFieldStyle(RoundedBorderTextFieldStyle()) .zIndex(1) } } struct View2: View { var body: some View { Color.clear } } struct View3: View { var body: some View { Color.black // (Ensure no transparency) } } zIndex() are not required, I just placed them to see if the problem get solved, but it may no difference. BTW, in the code above, the visible border disappears if the view is minimized, but that is not the case in the real app I'm working on. In the screenshots attached, it can be seen how the TextField border remains visible when view3 is active ("https://developer.apple.com/forums/content/attachment/d0e75f25-d36e-4361-af64-54252d1f2a98" "title=Screenshot 2024-05-24 at 10.06.03 PM.png;width=800;height=632")
0
0
226
May ’24
(Swift) TextField border contained in a view remains visible even when the view is fully overlapped by another view.
I have a ZStack that contains a VStack with 2 views (view1 and view2) and a third view (view3). So, is either that view1 and View1 are visible, or view3 is visible. This is the relevant code: ZStack { VStack { view1() View2() } if showView3 View3() } view1 and view2 are 400px in width and 200px in height, while view3 is 400 x 400 px, so that it completely overwrite view1/view2 when visible. The problem I'm trying to solve is that the border of a TextField placed in view1 is visible when showView3 is true, what should not be happening (possible glitch in swift?). To show the problem, I prepared a code sample, which shows that when view3 is active, it completely overwrites view1/view2, but still, the border of the TextField remains visible. (See screenshot below) struct TestZStackView: View { @State private var showView3 = false var body: some View { ZStack { VStack { Toggle("view3", isOn: $showView3) View1() .frame(width: 400, height: 200) .background(Color.red) .zIndex(1) View2() .frame(width: 400, height: 200) .background(Color.green) .zIndex(1) } if showView3 { View3() .frame(width: 400, height: 400) .background(Color.blue) .zIndex(2) } } } } struct View1: View { var body: some View { TextField("Enter text", text: .constant("")) .padding() .cornerRadius(5) .textFieldStyle(RoundedBorderTextFieldStyle()) .zIndex(1) } } struct View2: View { var body: some View { Color.clear } } struct View3: View { var body: some View { Color.black // (Ensure no transparency) } } zIndex() are not required, I just placed them to see if the problem get solved, but it may no difference. BTW, in the code above, the visible border disappears if the view is minimized, but that is not the case in the real app I'm working on. In the screenshots attached, it can be seen how the TextField border remains visible when view3 is active ("https://developer.apple.com/forums/content/attachment/d0e75f25-d36e-4361-af64-54252d1f2a98" "title=Screenshot 2024-05-24 at 10.06.03 PM.png;width=800;height=632")
0
0
221
May ’24
"Unexpectedly found nil while unwrapping an Optional value" in URL
Before anyone rants and raves about checking documentation - I have spent the last 4 hours trying to solve this issue on my own before asking for help. Coding in Swift is VERY new for me and I'm banging my head against the wall trying to teach myself. I am very humbly asking for help. If you refer me to documentation, that's fine but I need examples or it's going to go right over my head. Teaching myself is hard, please don't make it more difficult. I have ONE swift file with everything in it. import Foundation import Cocoa import Observation class GlobalString: ObservableObject { @Published var apiKey = "" @Published var link = "" } struct ContentView: View { @EnvironmentObject var globalString: GlobalString var body: some View { Form { Section(header: Text("WallTaker for macOS").font(.title)) { TextField( "Link ID:", text: $globalString.link ) .disableAutocorrection(true) TextField( "API Key:", text: $globalString.apiKey ) .disableAutocorrection(true) Button("Take My Wallpaper!") { } } .padding() } .task { await Wallpaper().fetchLink() } } } @main struct WallTaker_for_macOSApp: App { @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true @EnvironmentObject var globalString: GlobalString var body: some Scene { WindowGroup { ContentView() .environmentObject(GlobalString()) } // MenuBarExtra("WallTaker for macOS", systemImage: "WarrenHead.png", isInserted: $showMenuBarExtra) { // Button("Refresh") { //// currentNumber = "1" // } // Button("Love It!") { //// currentNumber = "2" // } // Button("Hate It!") { //// currentNumber = "3" // } // Button("EXPLOSION!") { // // currentNumber = "3" // } //// // } } } class Wallpaper { var url: URL? = nil var lastPostUrl: URL? = nil let mainMonitor: NSScreen init() { mainMonitor = NSScreen.main! } struct LinkResponse: Codable { var post_url: String? var set_by: String? var updated_at: String } struct Link { var postUrl: URL? var setBy: String var updatedAt: Date } func parseIsoDate(timestamp: String) -> Date? { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter.date(from: timestamp) } func fetchLink() async { do { url = URL(string: GlobalString().link) let (data, _) = try await URLSession.shared.data(from: url!) let decoder = JSONDecoder() let linkResponse = try decoder.decode(LinkResponse.self, from: data) let postUrl: URL? = linkResponse.post_url != nil ? URL(string: linkResponse.post_url!) : nil let date = parseIsoDate(timestamp: linkResponse.updated_at) let link = Link( postUrl: postUrl, setBy: linkResponse.set_by ?? "anon", updatedAt: date ?? Date() ) try update(link: link) } catch { } } func update(link: Link) throws { guard let newPostUrl = link.postUrl else { return } if (newPostUrl != lastPostUrl) { lastPostUrl = newPostUrl let tempFilePath = try getTempFilePath() try downloadImageTo(sourceURL: newPostUrl, destinationURL: tempFilePath) try applyWallpaper(url: tempFilePath) } else { } } private func applyWallpaper(url: URL) throws { try NSWorkspace.shared.setDesktopImageURL(url, for: mainMonitor, options: [:]) } private func getTempFilePath() throws -> URL { let directory = NSTemporaryDirectory() let fileName = NSUUID().uuidString let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])! return fullURL } private func downloadImageTo(sourceURL: URL, destinationURL: URL) throws { let data = try Data(contentsOf: sourceURL) try data.write(to: destinationURL) } } The 'fetchLink' function is where things explode, specifically when setting the URL. I do not know what I'm doing wrong.
5
0
381
2w
Swift: Declaration name is not covered by macro
Hello! I'm trying to generate a protocol dependent for another one using Swift macros. The implementation looks like the following: @attached (peer, names: suffixed (Dependent),prefixed (svc)) public macro dependableService() = #externalMacro (module: "Macros", type: "DependableServiceMacro") public struct DependableServiceMacro: PeerMacro { public static func expansion (of node: AttributeSyntax, providingPeersOf declaration: some DeclSyntaxProtocol, in context: some MacroExpansionContext) throws -> [DeclSyntax] { guard let baseProto = declaration.as (ExtensionDeclSyntax.self) else { return [] } let nm = baseProto.extendedType.trimmedDescription let protoNm = nm + "Dependent" let varNm = "svc" + nm let protoDecl: DeclSyntax = """ protocol \(raw: protoNm) : ServiceDependent { var \(raw: varNm) : \(raw: nm) { get set } } """ return [protoDecl] } } When I try using it in my code like this @dependableService extension MyService {} the macro correctly expands to the following text: protocol MyServiceDependent : ServiceDependent { var svcMyService : MyService { get set } } However, the compiler gives me the error: error: declaration name 'MyServiceDependent' is not covered by macro 'dependableService' protocol MyServiceDependent : ServiceDependent { ^ Do I understand correctly, that for some reason the compiler cannot deduce the name of the generated protocol based on the name of the extensible protocol, despite the presence of the names: suffixed(Dependent) attribute in the macro declaration? Could anybody please tell me what I'm doing wrong here? Thanks in advance
1
0
276
May ’24
SwiftData does not retrieve my inverse one-to-many Relationship
Here is my models: import SwiftData @Model final public class FirstModel { let name: String @Relationship(deleteRule: .cascade, inverse: \SecondModel.parent) var children = [SecondModel]() init(name: String) { self.name = name } } @Model final public class SecondModel { let parent: FirstModel let name: String @Relationship(deleteRule: .cascade, inverse: \ThirdModel.parent) var children = [ThirdModel]() init(name: String, parent: FirstModel) { self.name = name self.parent = parent } } @Model final public class ThirdModel { let parent: SecondModel let name: String init(name: String, parent: SecondModel) { self.name = name self.parent = parent } } Then I create my model entries: let schema = Schema([ FirstModel.self, SecondModel.self, ThirdModel.self ]) let container = try ModelContainer(for: schema) let context = ModelContext(container) let firstModel = FirstModel(name: "my first model") let secondModel = SecondModel(name: "my second model", parent: firstModel) let thirdModel = ThirdModel(name: "my third model", parent: secondModel) context.insert(firstModel) context.insert(secondModel) context.insert(thirdModel) try context.save() I want to retrieve the children from my models: print("-- Fetch Third Model") let thirdFetchDescriptor: FetchDescriptor<ThirdModel> = FetchDescriptor<ThirdModel>(predicate: #Predicate { $0.name == "my third model" }) let thirdModels = try context.fetch(thirdFetchDescriptor) for entry in thirdModels { print(">>> \(entry) - \(entry.parent) - \(entry.parent.parent)") } print("-- Fetch First Model") let firstFetchDescriptor: FetchDescriptor<FirstModel> = FetchDescriptor<FirstModel>(predicate: #Predicate { $0.name == "my first model" }) let firstModels = try context.fetch(firstFetchDescriptor) for entry in firstModels { print(">>> \(entry) - \(entry.children)") for child in entry.children { print("\t>>> \(child) - \(child.children)") } } ... But it does not seem to work: -- Fetch Third Model >>> cardapart_sdk_app_ui.ThirdModel - cardapart_sdk_app_ui.SecondModel - cardapart_sdk_app_ui.FirstModel -- Fetch First Model >>> cardapart_sdk_app_ui.FirstModel - [] What I would expect to see: -- Fetch First Model >>> cardapart_sdk_app_ui.FirstModel - [cardapart_sdk_app_ui.SecondModel] >>> cardapart_sdk_app_ui.SecondModel - [cardapart_sdk_app_ui.ThirdModel] I am not sure what I am doing wrong or missing...
1
0
299
May ’24
SwiftUI: How do I tell when my device orientation changes
Sorry to repeat this, but the new style forum won't allow me access to the original version of this question, and the answers. I have been searching the internet for 3 or 4 days now to find only complex solutions that I cannot get working. All I want to do is determine when the device orientation changes so that I can update the background Image. This is what I have so far: Import SwiftUI struct Main_Menu_iPhone: View { @State private var bloodGlucose: Float = 0.0 var body: some View { ZStack { Image("iPhone Background Portrait 828 x 1792 ") .resizable() .aspectRatio(contentMode: .fill) VStack { HStack { Label("Blood Glucose", systemImage: "drop.fill") TextField("Blood Glucose : ", value: $bloodGlucose, format: .number) .onSubmit() { print("Your Blood Gluse is : \(bloodGlucose)") } .background(.white) .frame(alignment: .topTrailing) Spacer() } Spacer() }.padding(.top, 250) } } }
1
0
368
May ’24
Game Center fetchSavedGames sometimes returns empty list of games, although it works correctly on the next tries
I have implemented the Game Center for authentication and saving player's game data. Both authentication and saving player's data works correctly all the time, but there is a problem with fetching and loading the data. The game works like this: At the startup, I start the authentication After the player successfully logs in, I start loading the player's data by calling fetchSavedGames method If a game data exists for the player, I receive a list of SavedGame object containing the player's data The problem is that after I uninstall the game and install it again, sometimes the SavedGame list is empty(step 3). But if I don't uninstall the game and reopen the game, this process works fine. Here's the complete code of Game Center implementation: class GameCenterHandler { public func signIn() { GKLocalPlayer.local.authenticateHandler = { viewController, error in if let viewController = viewController { viewController.present(viewController, animated: false) return } if error != nil { // Player could not be authenticated. // Disable Game Center in the game. return } // Auth successfull self.load(filename: "TestFileName") } } public func save(filename: String, data: String) { if GKLocalPlayer.local.isAuthenticated { GKLocalPlayer.local.saveGameData(Data(data.utf8), withName: filename) { savedGame, error in if savedGame != nil { // Data saved successfully } if error != nil { // Error in saving game data! } } } else { // Error in saving game data! User is not authenticated" } } public func load(filename: String) { if GKLocalPlayer.local.isAuthenticated { GKLocalPlayer.local.fetchSavedGames { games, error in if let game = games?.first(where: {$0.name == filename}){ game.loadData { data, error in if data != nil { // Data loaded successfully } if error != nil { // Error in loading game data! } } } else { // Error in loading game data! Filename not found } } } else { // Error in loading game data! User is not authenticated } } } I have also added Game Center and iCloud capabilities in xcode. Also in the iCloud section, I selected the iCloud Documents and added a container. I found a simillar question here but it doesn't make things clearer.
0
0
204
May ’24
Weird Swift overriding cocoapods
I don't even use Swift. I use Flutter. I am getting this odd always_embed_swift library warning that seems to be overriding my runner target on xcode. I'll just attach the image down below of what I'm dealing with. Please an apple engineer or someone just help me because this has been a struggle lol. I need to change this but can't find the setting to do so.
0
0
198
May ’24
SwiftUI: How do I detect a change in device orientation?
Please can someone help I have spent 3 - 4 days trawling the internet and only finding complex answers that I can't get to work, and my head is ready to explode. I only want to detect when the device orientation has changed and load a different background image. This is what I have so far: import SwiftUI struct Main_Menu_iPhone: View { @State private var bloodGlucose: String = "0.0" var body: some View { ZStack { Image("iPhone Background Portrait 828 x 1792 ") .resizable() .aspectRatio(contentMode: .fill) VStack { TextField("Blood Glucose : ", text: $bloodGlucose) Spacer() } } } } #Preview { Main_Menu_iPhone() }
2
0
316
May ’24
How might I get didSet behaviour on an AppStorage var?
I've defined a value stored in UserDefaults. In a view struct I have code that can successfully update the stored value. I've also added an @AppStorage var in an instance of a class, that can read this value and run business logic that depends on the current stored value. But what I really want to do, is have code in my class that gets automatically called when the value stored in UserDefaults gets updated. Basically I want to do this: @AppStorage("languageChoice") var languageChoice: LanguageChoice = .all { didSet { print("hello") } } Unfortunately didSet closures in @AppStorage vars do not appear to get called :-( My clumsy attempts to use combine have all ended in tears from the compiler. Any/all suggestions are greatly appreciated. thanks, Mike
3
0
287
3w
Storing Different Types of Swift Objects in C++ Using New Interop
Hello Everyone, I'm working on an app that utilizes the new C++ - Swift interop feature. I have a module called ModuleA that contains multiple Swift classes, and I need to store instances of these classes in a C++ class as a class member(to ensure ARC until the class object is deallocated). However, I want to retain the Swift class objects on the stack without directly allocating heap memory from C++. Sample Swift Code: public class SwiftClassA { public init() {} public func FuncA() -&gt; Void { // Perform operations specific to SwiftClassA } } public class SwiftClassB { public init() {} public func FuncA() -&gt; Void { // Perform operations specific to SwiftClassB } } // Additional Swift classes (SwiftClassC to SwiftClassN) follow a similar structure. Sample Cpp Code: CppClass.hpp #include "ModuleA-Swift.h" // Include generated Swift headerclass CppClass { public: // Functions and declarationsprivate: XYZ vClassObject; // Placeholder for Any Swift class object }; CppClass.cpp #include "ModuleA-Swift.h" // Include generated Swift headervoid CppClass::SomeFuncA() noexcept { ModuleA::SwiftClassA obj = ModuleA::SwiftClassA::init(); // Initialize SwiftClassA object vClassObject = obj; // Assign SwiftClassA object to vClassObject } void CppClass::SomeFuncB() noexcept { ModuleA::SwiftClassB obj = ModuleA::SwiftClassB::init(); // Initialize SwiftClassB object vClassObject = obj; // How do I Assign SwiftClassB object to vClassObject? } I'm looking for suggestions on how to efficiently store different types of Swift class objects in my C++ class while maintaining stack-based object retention and proper memory management. Any help or insights would be greatly appreciated. Thanks, Harshal
4
0
374
4w
How to get selected usdz model thumbnail image using QuickLookThumbnailing
I am doing below code for getting thumbnail from usdz model using the QuickLookThumbnailing, But don't get the proper out. guard let url = Bundle.main.url(forResource: resource, withExtension: withExtension) else{ print("Unable to create url for resource.") return } let request = QLThumbnailGenerator.Request(fileAt: url, size: size, scale: 10.0, representationTypes: .all) let generator = QLThumbnailGenerator.shared generator.generateRepresentations(for: request) { thumbnail, type, error in DispatchQueue.main.async { if thumbnail == nil || error != nil { print(error) }else{ let tempImage = Image(uiImage: thumbnail!.uiImage) print(tempImage) self.thumbnailImage = Image(uiImage: thumbnail!.uiImage) print("=============") } } } } Below Screen Shot for selected model : Below is the thumbnail image, which not come with guitar but get only usdz icon.
1
0
257
May ’24
How to get selected usdz model thumbnail image with material apply in vision os?
I want to get thumbnail image from USDZ model from vision os, But it will get image without material apply. Here is my code import Foundation import SceneKit import SceneKit.ModelIO class ARQLThumbnailGenerator { private let device = MTLCreateSystemDefaultDevice()! /// Create a thumbnail image of the asset with the specified URL at the specified /// animation time. Supports loading of .scn, .usd, .usdz, .obj, and .abc files, /// and other formats supported by ModelIO. /// - Parameters: /// - url: The file URL of the asset. /// - size: The size (in points) at which to render the asset. /// - time: The animation time to which the asset should be advanced before snapshotting. func thumbnail(for url: URL, size: CGSize, time: TimeInterval = 0) -> UIImage? { let renderer = SCNRenderer(device: device, options: [:]) renderer.autoenablesDefaultLighting = true if (url.pathExtension == "scn") { let scene = try? SCNScene(url: url, options: nil) renderer.scene = scene } else { let asset = MDLAsset(url: url) let scene = SCNScene(mdlAsset: asset) renderer.scene = scene } let image = renderer.snapshot(atTime: time, with: size, antialiasingMode: .multisampling4X) self.saveImageFileInDocumentDirectory(imageData: image.pngData()!) return image } func saveImageFileInDocumentDirectory(imageData : Data){ var uniqueID = UUID().uuidString let tempPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) let tempDocumentsDirectory: AnyObject = tempPath[0] as AnyObject let uniqueVideoID = uniqueID + "image.png" let tempDataPath = tempDocumentsDirectory.appendingPathComponent(uniqueVideoID) as String try? imageData.write(to: URL(fileURLWithPath: tempDataPath), options: []) } }
1
0
230
May ’24
Alternative option to initial onChange callback for EmptyView
I am exploring on managing state in SwiftUI app with purpose built Views due to the advantages for managing dependency with Environment. This is the minimal example I came up with: @MainActor struct AsyncStateModifier<T: Equatable>: View { let input: T let action: (T) async -> Void @Environment var queue: AsyncActionQueue var body: some View { return EmptyView() .onChange(of: input, initial: true) { old, new in queue.process(action: action, with: input) } } } The drawback of this approach is initial: true allows the onChange callback to fire when view appears and since EmptyView doesn't appear the action is never executed initially. When replacing EmptyView with Rectangle().hidden() this can be achieved, but I wanted to avoid having any impact on view hierarchy and EmptyView is suitable for that. Is there any alternative approach to make something like this possible?
1
0
193
May ’24
How to use .a in swift with an empty header
I'm making a Swift Program. I got a .a file that builded from some c++ scripts,and I can see some fuctions in it by commed "nm *.a", and a .h file like this My question is how to call the fuctions in .a like "testDebug",I can call from c# like [DllImport("__Internal")] private static extern void testDebug(); Google's answer always with a right .h file,Maybe I should make .h file correct first. Any reply would be greatly appreciated.
2
0
233
May ’24
Swift: Can I change views without clicking on a link.
I want to automatically load different views depending on OS (OSX or iOS). Is there a way that I can do this without the user having to click on a link? This is my code so far. struct ContentView: View { #if os(iOS) var myOS = "iOS" #elseif os(OSX) var myOS = "OSX" #else var myOS = "Something Else" #endif var body: some View { NavigationStack { VStack { Text("PLEASE WAIT....") .font(.system(size: 24)) .fontWeight(.bold) } .padding() if (myOS == "OSX"){ // Goto Screen for iMac } else{ // go to screen for iOS } } } } If I use "NavigationLink", my understanding is that the user would need to click on a link. Is there some way to do this without user interaction?
2
0
205
May ’24
Problem with NavigationStack(path:)
Hello everyone. I am developing an application with SwiftUI. I am having trouble with NavigationStack(path: ). 1st problem: After the application runs, after clicking on the first list item, there is a flicker in the title section. I think it is the .navigationDestination that causes this problem, because when I change the navigationLink to Button in the “ActiveRegQueryView” screen, this problem disappears. 2nd Problem: When you click on a list item, sometimes it stays pressed (grayed out) and does not take you to the screen (Video 1). If you try to click on an item more than once, navigatinLink passes more than one value to path and opens more than one page (I noticed this with path.count) (Video 2). I don't have this problem if you edit the back button on the screen it takes you to (ActiveRegDetailView). (vm.path.removeLast()) The reason I use path is to close multiple screens and return to the start screen. Video 1: Video 2: Main View: import SwiftUI struct ActiveRegView: View { @Environment(NavigationViewModel.self) private var navViewModel @AppStorage("sortOption") private var sortOrder: sorting = .byBrand @State private var searchText = "" var body: some View { @Bindable var navViewModel = navViewModel NavigationStack(path: $navViewModel.path) { // <- if i don't use path everything is OK List { ActiveRegQueryView(searchText: searchText, sortOrder: sortOrder) // <- Dynamic Query View } .navigationDestination(for: Registration.self, destination: { ActiveRegDetailView(reg: $0) .toolbar(.hidden, for: .tabBar) }) } } } Dynamic Query View: import SwiftData import SwiftUI struct ActiveRegQueryView: View { @Query private var regs: [Registration] @Environment(NavigationViewModel.self) var vm init(searchText: String, sortOrder: sorting) { var order: SortDescriptor<Registration> switch sortOrder { case .byBrand: order = SortDescriptor(\.brand) case .byDateDescending: order = SortDescriptor(\.entryRegistration.entryDate, order: .reverse) case .byDateAscending: order = SortDescriptor(\.entryRegistration.entryDate) } _regs = Query(filter: #Predicate { if !searchText.isEmpty { if $0.activeRegistration && ($0.brand.localizedStandardContains(searchText) || $0.model.localizedStandardContains(searchText) || $0.plate.localizedStandardContains(searchText)) { return true } else { return false } } else { return $0.activeRegistration } }, sort: [order]) } var body: some View { ForEach(regs) { reg in NavigationLink(value: reg) { ListRowView(reg: reg) } // Button { // vm.path.append(reg) // } label: { // ListRowView(reg: reg) // } // .buttonStyle(.plain) } } } I look forward to your ideas for solutions. Thank you for your time.
0
0
208
May ’24