[英]Force view that conforms to protocol to have a property wrapper in SwiftUI
我想强制某些View
包含一个@Binding
属性,因此我为此创建了一个协议。
如下所示:
protocol DismissableView: View {
var isPresented: Binding<Bool> { get set }
}
当我希望我的视图符合它时,就像这样:
struct MyView: DismissableView {
@Binding var isPresented: Bool
}
我得到以下信息:
Type 'MyView' does not conform to protocol 'DismissableView'
我认为这与@Binding
与Binding<Bool>
不同的事实有关
正如你们都清楚的事实,我不能在协议中声明一个 propertyWrapper,因此我不能简单地在协议中直接声明一个 @Binding,我很困在这里。
我是什么做的?
以下是可能的变体:
a) 使用与协议相同的存储属性(缺点:通过wrappedValue
访问)
struct MyView: DismissableView {
var isPresented: Binding<Bool>
var body: some View {
Text(isPresented.wrappedValue ? "Presented" : "Not")
}
}
struct MyView: DismissableView {
var isPresented: Binding<Bool> {
get { _presented }
set { _presented = newValue }
}
@Binding var presented: Bool
// optional init if needed to have MyView(isPresented: Binding<Bool>) interface
// init(isPresented: Binding<Bool>) {
// self._presented = isPresented
// }
var body: some View {
Text(presented ? "Presented" : "Not")
}
}
两种情况下的外部使用是相同的。
注意: @Binding var isPresented: Bool
property wrapper is unwrapped 创建了两个属性(见下文),这就是您无法直接确认它的原因
var isPresented: Bool
var _isPresented: Binding<Bool>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.