从初始化程序返回而未初始化所有存储的属性-SwiftUI绑定错误

时间:2020-10-25 01:21:42

标签: ios swift swiftui uikit

我有几个级联模式,需要根据某些后台进程进行刷新。为了实现这一点,我创建了一个结构,在其中保存了UI的所有逻辑,并使用UIHostingController.init(rootView:views)调用了几个SwiftUI视图。

当我想通过单击子视图中的按钮来关闭视图时,挑战就来了。我正在尝试使用@State和@Binding,但是绑定迫使我在子视图内初始化变量。

这是孩子的代码:

struct ResultViewSilence: View {

@Binding var isDismissView: Bool
var hasSilence: Bool
let photolibrary = PhotoLibrary()

init(hasSilence: Bool) {
    self.hasSilence = hasSilence
    <--- here is where is asking to initialize isDismissView, but it should not be needed
}

通过执行此操作,我可以初始化isDismissView ...

init(hasSilence: Bool, isDismissView: Binding<Bool>?) {
    ...
    self._isDismissView = isDismissView!

但是,如果我这样做,它将在父级中中断,因为我无法在UIHostingController中将@State作为参数传递,这是必需的。

如果这样做,我将得到的错误是:

"Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update."

我还在检查@State变量,即使按钮被触发也没有改变。

干杯

1 个答案:

答案 0 :(得分:2)

import SwiftUI

struct ResultViewSilence: View {

    ///@State needs to be initialized here because it CAN store values
    ///https://developer.apple.com/documentation/swiftui/state
    @State var isDismissView1: Bool = false
    
    ///@Binding creates a 2 way connection does NOT store values needs a parent that stores values
    ///https://developer.apple.com/documentation/swiftui/binding
    @Binding var isDismissView2: Bool
    
    var hasSilence: Bool
    
    //let photolibrary = PhotoLibrary() //No code provided

    init(hasSilence: Bool, isDismissView2: Binding<Bool> ) {
        self.hasSilence = hasSilence
        self._isDismissView2 = isDismissView2
    }
    var body: some View {
        VStack{
            Text("isDismissView1 = " + isDismissView1.description)
            Text("isDismissView2 = " + isDismissView2.description)
        }
    }
}
struct ParentResultViewSilence: View {
    //Parent that can store values
    @State var isDismissView2: Bool = true
    var body: some View {
        ResultViewSilence(hasSilence: false, isDismissView2: $isDismissView2)
    }
}
struct ResultViewSilence_Previews: PreviewProvider {
    static var previews: some View {
        //ResultViewSilence(hasSilence: false, isDismissView2: .constant(true))
        ParentResultViewSilence()
    }
}