1

我有一个类似这样的 BaseView,我想为我的所有子视图添加警报机制

struct BaseView<Content: View>: View {
    @State var isAlertPresented = false
    let content: Content
    
    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }
    
    var body : some View {
        content.alert(isPresented: $isAlertPresented) {
            Alert(title: Text("title"))
        }
    }

}

这是我的子视图。

struct SubView: View {
    BaseView {
        Text("")
    }.onReceive(vm.publisher) { (output) in
        // here I want to trigger BaseView isAlertPresented property        
        // BaseView.isAlertPresented = true
    }
}

我可以做这样的事情吗?如果是,我该怎么办?

4

1 回答 1

1

如果 view 包含 BaseView 它绝对不是与之相关的子视图。并且您不应该因为违反单一事实来源而访问/操纵其他视图的内部状态。

相反,您必须在这种情况下使用绑定,如下所示(使用 Xcode 11.7 测试)

struct BaseView<Content: View>: View {
    @Binding var isAlertPresented: Bool
    let content: Content

    init(isAlertPresented: Binding<Bool>, @ViewBuilder content: () -> Content) {
        self._isAlertPresented = isAlertPresented
        self.content = content()
    }

    var body : some View {
        content.alert(isPresented: $isAlertPresented) {
            Alert(title: Text("title"))
        }
    }

}

struct SomeOtherView: View {
    @State private var showAlert = false

    var body: some View {
        BaseView(isAlertPresented: $showAlert) {
            Text("Test")
        }
        .onReceive(vm.publisher) { (output) in
//        .onAppear {     // used instead of above just for test
            self.showAlert = true
        }
    }
}
于 2020-09-08T11:35:51.177 回答