[英]How can I extend Picker with a custom initializer?
I am trying to get the following code to work:我正在尝试使以下代码正常工作:
extension Picker where Label == Text, SelectionValue == Bool {
init(selection: Binding<SelectionValue>) {
self.init("Bool", selection: selection) {
Text("TRUE").tag(true)
Text("FALSE").tag(false)
}
}
}
But get this compiler error:但是得到这个编译器错误:
Cannot convert value of type 'TupleView<(some View, some View)>' to closure result type 'Content'
无法将类型“TupleView<(some View, some View)>”的值转换为闭包结果类型“Content”
The goal is to be able to create a picker the following way:目标是能够通过以下方式创建选择器:
@State private var value = false
var body: some View {
Form {
Picker($value)
}
}
I understand that the compiler tries to infer Content
from the caller of the initializer, but since I am calling an existing initializer and provide it with content, why am I still seeing this error?我了解编译器试图从初始化程序的调用者推断
Content
,但由于我正在调用现有初始化程序并为其提供内容,为什么我仍然看到此错误?
You specified what the Label
and SelectedValue
types for the Picker
should be in the extension header, but not Content
, so this initialiser is added to pickers with all kinds of content types.您指定了选择
Picker
的Label
和SelectedValue
类型应该在扩展 header 中,而不是Content
,因此这个初始化程序被添加到具有各种内容类型的选择器中。 But you don't really want that, do you?但你并不是真的想要那样,是吗? This initialiser only produces pickers with this specific type of
Content
:此初始化程序仅生成具有此特定类型
Content
的选择器:
{
Text("TRUE").tag(true)
Text("FALSE").tag(false)
}
But we can't really name the type of that, because it's TupleView<(some View, some View)>
, and opaque types can't be used like that:但是我们不能真正命名它的类型,因为它是
TupleView<(some View, some View)>
,并且不能像这样使用不透明类型:
// nope!
extension Picker where Label == Text, SelectionValue == Bool, Content == TupleView<(some View, some View)> {
One way to work around this is to wrap the Text
s in AnyView
s:解决此问题的一种方法是将
Text
包装在AnyView
中:
extension Picker where Label == Text, SelectionValue == Bool, Content == TupleView<(AnyView, AnyView)> {
init(_ selection: Binding<SelectionValue>) {
self.init("Bool", selection: selection) {
AnyView(Text("TRUE").tag(true))
AnyView(Text("FALSE").tag(false))
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.