为什么 init() 在尝试传递数据时会影响 Navigation Link?

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

我正在尝试自定义导航栏。当我尝试在 second 视图上使用 init() 时,出现错误“Argument passed to call that takes no arguments.”我有一个 class 和两个简单​​的视图。

Class

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

第一次观看

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")
                })
            }
        }
    }
}

第二个视图

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)
    }
}

如果您要定义自己的初始值设定项,则必须定义参数并将它们分配给您的属性,Xcode 通常会为您合成这些参数。在这种情况下,它需要一个参数 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)
    }
}