简体   繁体   English

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

[英]Force view that conforms to protocol to have a property wrapper in SwiftUI

I want to enforce certain View s to contain a @Binding property thus I created a protocol for this.我想强制某些View包含一个@Binding属性,因此我为此创建了一个协议。

Like the following:如下所示:

protocol DismissableView: View {
   var isPresented: Binding<Bool> { get set }
}

And when I want my View to conform to it, Like this:当我希望我的视图符合它时,就像这样:

struct MyView: DismissableView {
   @Binding var isPresented: Bool 
}

I get the following:我得到以下信息:

Type 'MyView' does not conform to protocol 'DismissableView'

which I reckon is got to do with the fact that @Binding is not the same as Binding<Bool>我认为这与@BindingBinding<Bool>不同的事实有关

As you all are obviously aware of the fact that I cannot decalare a propertyWrapper in a protocol thus I am unable to simply declare in the protocol a @Binding directly, I am pretty stuck here.正如你们都清楚的事实,我不能在协议中声明一个 propertyWrapper,因此我不能简单地在协议中直接声明一个 @Binding,我很困在这里。

What am I to do?我是什么做的?

Here are possible variants:以下是可能的变体:

a) use stored property the same as in protocol (drawback: access via wrappedValue ) a) 使用与协议相同的存储属性(缺点:通过wrappedValue访问)

struct MyView: DismissableView {

    var isPresented: Binding<Bool>

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

External usage in both cases is same.两种情况下的外部使用是相同的。

Note: the @Binding var isPresented: Bool property wrapper being unwrapped creates two properties (see below) that is why you cannot confirm it directly注意: @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