1

When you compile below code and enter "J" in the search field and then click one of the entries, the app crashes when showing the NavigationLink destination. Clicking on an entry without any active filter works fine.

import SwiftUI
import Combine



public class Person: Identifiable, ObservableObject {
    public var id = UUID()
    var firstName: String = ""
    var lastName: String = ""
}

struct PersonView: View{
    @ObservedObject var person: Person = Person()
    @State public var navigationBarTitle: String = "New item"
    
    var body: some View{
        Group{
            VStack{
                Form{
                    Section(header: Text("Some section")){
                        Text("Detail for \(person.firstName) \(person.lastName)")
                    }
                    
                }
            }
        }//Group
        .navigationBarTitle(self.navigationBarTitle)
        .navigationBarItems(leading: (
            EmptyView()
        ), trailing: (
            Button(action: {
                print("-------SAVE-------")
            }, label: {
                Text("Save")
            }
                  )
        ))
    }
}

struct ContentView: View {
    @State var persons: [Person] = []
    @State var searchText = ""
    
    var searchResults: [Person] {
        if searchText.isEmpty {
            return persons
        } else {
            return persons.filter { $0.firstName
                    .lowercased()
                    .contains(searchText.lowercased())
                ||
                $0.lastName
                    .lowercased()
                    .contains(searchText.lowercased())
            }
        }
    }
    
    var body: some View {
        TabView{
            NavigationView{
                ZStack{
                    List{
                        ForEach(searchResults){person in
                            NavigationLink(destination: PersonView(person: person)) {
                                Text("\(person.firstName) \(person.lastName)")
                            }
                        }//ForEach
                        .listStyle(.plain)
                    }//List
                    .refreshable {
                        print("refresh triggered")
                    }
                    .searchable(text: $searchText)
                }//ZStack
                .toolbar(content: {
                    ToolbarItem{
                        Button {
                            print("button pressed")
                        } label: {
                            Image(systemName: "line.3.horizontal.decrease.circle.fill")
                        }
                    }
                })
                .navigationTitle("Persons")
                
            }//NavigationView
            .onAppear(){
                self.initPersons()
            }
            .tabItem {
                Image(systemName: "rectangle.on.rectangle")
                Text("Persons")
            }
        }
        
        
    }
    
    func initPersons(){
        let person = Person()
        person.firstName = "John"
        person.lastName = "Doe"
        
        let person1 = Person()
        person1.firstName = "Jane"
        person1.lastName = "Doe"
        
        let person2 = Person()
        person2.firstName = "Tim"
        person2.lastName = "Appleseed"
        
        let person3 = Person()
        person3.firstName = "Sally"
        person3.lastName = "Snickers"
        
        self.persons.append(person)
        self.persons.append(person1)
        self.persons.append(person2)
        self.persons.append(person3)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I have noticed that when I remove the code block

.navigationBarItems(leading: (
            EmptyView()
        ), trailing: (
            Button(action: {
                print("-------SAVE-------")
            }, label: {
                Text("Save")
            }
                  )
        ))

from the PersonView view, it works fine. What am I missing here?

UPDATED CODE BELOW BASED ON LOREM IPSUM's recommendation, still does not solve the issue:

import SwiftUI
import Combine



public class Person: Identifiable, ObservableObject {
    public var id = UUID()
    var firstName: String = ""
    var lastName: String = ""
}

struct PersonView: View{
    @ObservedObject var person: Person = Person()
    @State public var navigationBarTitle: String = "New item"
    
    var body: some View{
        Group{
            VStack{
                Form{
                    Section(header: Text("Some section")){
                        Text("Detail for \(person.firstName) \(person.lastName)")
                    }
                    
                }
            }
        }//Group
        .toolbar {
            ToolbarItem(placement: .primaryAction, content: {
                Button("Save"){
                    print("Saved")
                }
            })
        }
        .navigationTitle(self.navigationBarTitle)
    }
}

struct ContentView: View {
    @State var persons: [Person] = []
    @State var searchText = ""
    
    var searchResults: [Person] {
        if searchText.isEmpty {
            return persons
        } else {
            return persons.filter { $0.firstName
                    .lowercased()
                    .contains(searchText.lowercased())
                ||
                $0.lastName
                    .lowercased()
                    .contains(searchText.lowercased())
            }
        }
    }
    
    var body: some View {
        TabView{
            NavigationView{
                ZStack{
                    List{
                        ForEach(searchResults){person in
                            NavigationLink(destination: PersonView(person: person)) {
                                Text("\(person.firstName) \(person.lastName)")
                            }
                        }//ForEach
                        .listStyle(.plain)
                    }//List
                    .refreshable {
                        print("refresh triggered")
                    }
                    .searchable(text: $searchText)
                }//ZStack
                .toolbar(content: {
                    ToolbarItem{
                        Button {
                            print("button pressed")
                        } label: {
                            Image(systemName: "line.3.horizontal.decrease.circle.fill")
                        }
                    }
                })
                .navigationTitle("Persons")
                
            }//NavigationView
            .onAppear(){
                self.initPersons()
            }
            .tabItem {
                Image(systemName: "rectangle.on.rectangle")
                Text("Persons")
            }
        }
        
        
    }
    
    func initPersons(){
        let person = Person()
        person.firstName = "John"
        person.lastName = "Doe"
        
        let person1 = Person()
        person1.firstName = "Jane"
        person1.lastName = "Doe"
        
        let person2 = Person()
        person2.firstName = "Tim"
        person2.lastName = "Appleseed"
        
        let person3 = Person()
        person3.firstName = "Sally"
        person3.lastName = "Snickers"
        
        self.persons.append(person)
        self.persons.append(person1)
        self.persons.append(person2)
        self.persons.append(person3)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Max B
  • 193
  • 1
  • 15
  • Use toolbar instead of navigstionBarItems it has been deprecated for a while and doesn’t work well with the newer features, change to navigationTitle too. – lorem ipsum Jul 01 '22 at 21:54
  • @loremipsum already tried that after posting here, same issue. Only "fix" is to use toolbar and bottom placement, then it works. – Max B Jul 01 '22 at 22:03
  • Try changing the observed object to a state object – lorem ipsum Jul 01 '22 at 22:45
  • unfortunately same result – Max B Jul 01 '22 at 22:49
  • I was able to prevent the issue from happening. Still investigating, but here is a bit of a hacky workaround. In your PersonView, modify your navigation bar title to be of type .inline. I.e. navigationBarTitle(self.navigationBarTitle, displayMode: .inline) - I will still investigate, but hope this helps in the short term. – nickreps Jul 02 '22 at 01:42

1 Answers1

1

you could try a small re-structure of your code and the following approach, using one class PersonsModel: ObservableObject for the view model, and struct Person, such as:

public class PersonsModel: ObservableObject {  // <-- here
    @Published var persons: [Person] = []
}

struct Person: Identifiable {  // <-- here
    let id = UUID()
    var firstName: String = ""
    var lastName: String = ""
}

struct PersonView: View{
    @State var person: Person   // <-- here
    @State public var navigationBarTitle: String = "New item"
    
    var body: some View{
        Group{
            VStack{
                Form{
                    Section(header: Text("Some section")){
                        Text("Detail for \(person.firstName) \(person.lastName)")
                    }
                    
                }
            }
        }//Group
        .toolbar {
            ToolbarItem(placement: .primaryAction, content: {
                Button("Save"){
                    print("Saved")
                }
            })
        }
        .navigationTitle(navigationBarTitle)
    }
}

struct ContentView: View {
    @StateObject var viewModel = PersonsModel() // <-- here
    @State var searchText = ""
    
    var searchResults: [Person] {
        if searchText.isEmpty {
            return viewModel.persons
        } else {
            return viewModel.persons.filter { $0.firstName
                    .lowercased()
                    .contains(searchText.lowercased())
                ||
                $0.lastName
                    .lowercased()
                    .contains(searchText.lowercased())
            }
        }
    }
    
    var body: some View {
        TabView{
            NavigationView{
                ZStack{
                    List{
                        ForEach(searchResults){ person in
                            NavigationLink(destination: PersonView(person: person)) {
                                Text("\(person.firstName) \(person.lastName)")
                            }
                        }//ForEach
                        .listStyle(.plain)
                    }//List
                    .refreshable {
                        print("refresh triggered")
                    }
                    .searchable(text: $searchText)
                }//ZStack
                .toolbar(content: {
                    ToolbarItem{
                        Button {
                            print("button pressed")
                        } label: {
                            Image(systemName: "line.3.horizontal.decrease.circle.fill")
                        }
                    }
                })
                .navigationTitle("Persons")
                
            }//NavigationView
            .onAppear(){
                initPersons()
            }
            .tabItem {
                Image(systemName: "rectangle.on.rectangle")
                Text("Persons")
            }
        }
    }
    
    func initPersons() {
        let person = Person(firstName: "John", lastName: "Doe")
        let person1 = Person(firstName: "Jane", lastName: "Doe")
        let person2 = Person(firstName: "Tim", lastName: "Appleseed")
        let person3 = Person(firstName: "Sally", lastName: "Snickers")
        
        viewModel.persons.append(person)
        viewModel.persons.append(person1)
        viewModel.persons.append(person2)
        viewModel.persons.append(person3)
    }
}

I think that in your original ContentView using @State var persons: [Person] with class Person: ObservableObject is not a good idea.