状态变量导致导航链接缺少初始化

时间:2020-10-01 23:42:41

标签: swiftui

在aboutabout(ContentView的底部)的导航链接上出现一些奇怪的错误:

    由于“私人”保护级别,无法访问
  1. aboutView”初始化程序
  2. 呼叫中缺少参数'useHomeCur'的参数
  3. 期望的表达式 Xcode还建议我在ContentView中插入',useHomeCur:<#Bool#>'

我在任何其他视图中都没有得到这些错误。 aboutView.swift中没有发生错误。它就像aboutView是ContentView的子视图一样。希望我在ContentView中定义aboutView状态参数。为什么?如果我在aboutView中输入状态参数和选项,则效果很好。

我也尝试过:.navigationBarItems(追踪:NavigationLink(目的地:aboutView()){ 文字(“关于”)。这种编码消除了预期的表达错误

iOS 14.0 Xcode 12.0.1 Galen

struct ContentView: View {

    @State private var activateAbout = false
    
    var body: some View {
        
        NavigationView {
            VStack {
                
                   ... menu navigation links
            }
            .font(.title)
            .navigationBarTitle("blah blah blah", displayMode: .inline)
            .background(
                // hide programmatically activated link here !!
                NavigationLink(destination: aboutView(), isActive: $activateAbout) { EmptyView()
            )
                    .navigationBarItems(trailing: Button( action: {
                    // not add - only activate it here, otherwise it will not work
                        self.activateAbout = true
                    }) {
                        Text("About")
                    }
                }           
            }
            
            .onAppear(perform: loadCurrencies)
        }
    }
}

这里是关于视图>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

struct aboutView: View {
    
    @EnvironmentObject var userData: UserData
    @State private var useHomeCur: Bool
    
    var body: some View {

        NavigationView {
        Form {
                VStack (alignment: .center) {
                    Text("blah blah blah")
                    Text("blah blah blah")
                }.font(.body)
            
                Toggle(isOn: $useHomeCur) {
                    Text("Use this fancy feature")
               }.padding()

           NavigationLink(destination: docView()) {
                Text("Documentation")
            }
        }.navigationBarTitle("About", displayMode: .inline)
  
        }
    }
}

1 个答案:

答案 0 :(得分:0)

状态变量供内部View使用,因此应在内部进行初始化(以及将其设为私有的良好做法)。如果您需要状态具有超出尺寸的初始值,则可以在init中明确地进行设置,例如

  1. 内部初始化变量
struct aboutView: View {
    
    @EnvironmentObject var userData: UserData
    @State private var useHomeCur: Bool = false    // << here !!
  1. 外部初始化变量
struct aboutView: View {
    
    @EnvironmentObject var userData: UserData
    @State private var useHomeCur: Bool

    init(useHomeCur: Bool = false) {
       _useHomeCur = State(initialValue: useHomeCur)    // << here !!
    }
    ...