Search code examples
swiftswiftuiswiftui-navigationlink

Why does init() affect Navigation Link when trying to pass data?


I'm trying to customize my navigation bar. When I try to use init() on the second view, I get an error "Argument passed to call that takes no arguments." I have a class and two views for simplicity.

Class

class TestClass: ObservableObject {
    @Published var name: String = "Joe"
}

First View

struct ContentView: View {
    @StateObject var testVar = TestClass()
    var body: some View {
        NavigationView {
            VStack {
                Text(testVar.name)
                NavigationLink(destination: SecondScreen(testVar: testVar), label: {
                    Text("Second Screen")
                })
            }
        }
    }
}

Second View

struct SecondScreen: View {
    @ObservedObject var testVar: TestClass
    
    //This is where I'd normally put an init
    //The init() doesn't even have to be filled with anything either for the error to appear
    
    //Example
    //    init() {
    //        UINavigationBar.appearance().barTintColor = UIColor(Color("CustomExampleColor"))
    //        UINavigationBar.appearance().isTranslucent = true
    //        UINavigationBar.appearance().titleTextAttributes = [
    //            .font : UIFont(name: "CustomFont", size: 30)!]
    //    }
    var body: some View {
        Text("Hi \(testVar.name)")
            .navigationBarTitle("Title".uppercased())
            .navigationBarTitleDisplayMode(.inline)
    }
}

Solution

  • If you're defining your own initializer, you have to define the parameters and assign them to your properties, which Xcode normally synthesizes for you. In this case, it takes a parameter of testVar:

    struct SecondScreen: View {
        @ObservedObject var testVar: TestClass
        
        init(testVar: TestClass) { //<-- Here
            self.testVar = testVar //<-- Here
            UINavigationBar.appearance().barTintColor = UIColor(Color("CustomExampleColor"))
            UINavigationBar.appearance().isTranslucent = true
            UINavigationBar.appearance().titleTextAttributes = [
                .font : UIFont(name: "CustomFont", size: 30)!]
        }
        
        var body: some View {
            Text("Hi \(testVar.name)")
                .navigationBarTitle("Title".uppercased())
                .navigationBarTitleDisplayMode(.inline)
        }
    }