【发布时间】:2021-04-15 23:34:17
【问题描述】:
我可以在没有初始化的情况下将绑定传递给另一个视图,并且它工作得很好。但是,如果我尝试使用具有 init 的视图,我将无法克服错误。
struct ContentView: View {
// MARK: - PROPERTIES
@State private var showAlert = false
@State private var alert: Alert? = nil
@State private var alertTitle = ""
@State private var alertMessage = ""
// MARK: - BODY
var body: some View {
VStack {
Button(action: {
alertTitle = "Alert 1"
alertMessage = "From Main View"
showAlert.toggle()
}, label: {
Text("Show Parent Alert")
})
// MARK: - TESTVIEW1
TestView1(showAlert: $showAlert, alert: $alert, alertTitle: $alertTitle, alertMessage: $alertMessage)
} // END:VSTACK
.alert(isPresented: $showAlert, content: {
Alert(title: Text(alertTitle), message: Text(alertMessage), dismissButton: .default(Text("Close")))
})
}
}
struct TestView1: View {
// MARK: - PROPERTIES
@Binding var showAlert: Bool
@Binding var alert: Alert?
@Binding var alertTitle: String
@Binding var alertMessage: String
// MARK: - BODY
var body: some View {
VStack {
Button(action: {
alertTitle = "Alert 2"
alertMessage = "From TestView1"
showAlert.toggle()
}, label: {
Text("Show View-1 Alert")
})
TestView2(showAlert: $showAlert, alert: $alert, alertTitle: $alertTitle, alertMessage: $alertMessage)
} // END:VSTACK
}
}
这很好,但如果我有一个 init,我会收到错误“无法将 'Alert?.Type' 类型的值分配给类型 'Alert'”
struct TestView1: View {
// MARK: - PROPERTIES
@Binding var showAlert: Bool
@Binding var alert: Alert?
@Binding var alertTitle: String
@Binding var alertMessage: String
init(showAlert: Binding<Bool>, alert: Binding<Alert>, alertTitle: Binding<String>, alertMessage: Binding<String>) {
self.showAlert = false
self.alert = Alert?
self.alertTitle = ""
self.alertMessage = ""
}
【问题讨论】: