繁体   English   中英

强制符合协议的视图在 SwiftUI 中具有属性包装器

[英]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'

我认为这与@BindingBinding<Bool>不同的事实有关

正如你们都清楚的事实,我不能在协议中声明一个 propertyWrapper,因此我不能简单地在协议中直接声明一个 @Binding,我很困在这里。

我是什么做的?

以下是可能的变体:

a) 使用与协议相同的存储属性(缺点:通过wrappedValue访问)

struct MyView: DismissableView {

    var isPresented: Binding<Bool>

    var body: some View {
        Text(isPresented.wrappedValue ? "Presented" : "Not")
    }
}
  1. 使用带有包装器的内部变量以符合协议(缺点:在每个确认的视图中都需要包装器)
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM