SwiftUI:有条件地显示不同的工作表项目 [英] SwiftUI: show different sheet items conditionally
问题描述
我在尝试如何使用 .sheet(item:content:)
时失败了.我知道这里和其他平台上有很多信息,但我无法让它发挥作用...
I am failing miserably trying to wrap my head around how to use .sheet(item:content:)
. I know that there is a lot of information here and on other platforms, but I just cannot get it to work...
这是我想要的视图的抽象——我不知道我在这里做错了什么:
Here's an abstraction of the view I'd like to have – and I don't know what I am doing wrong here:
import SwiftUI
enum SheetView: String, Identifiable {
var id: Self { self }
case sheetA = "Sheet A"
case sheetB = "Sheet B"
}
struct SheetViewTest: View {
@State private var showSheet: SheetView? = nil
var body: some View {
Form {
Button(action: {
showSheet = .sheetA
print("Button \(showSheet?.rawValue) tapped…")
}, label: {
Text(SheetView.sheetA.rawValue)
})
Button(action: {
showSheet = .sheetB
print("Button \(showSheet?.rawValue) tapped…")
}, label: {
Text(SheetView.sheetB.rawValue)
})
}
.sheet(item: $showSheet) { sheet -> View in
Text(sheet.rawValue)
}
}
}
struct SheetViewTest_Previews: PreviewProvider {
static var previews: some View {
SheetViewTest()
}
}
我在身体上的错误如下:协议类型'View'的值不能符合'View';只有 struct/enum/class 类型可以符合协议
,这是由于 .sheet
修饰符导致当我将其注释掉时,视图工作正常...
The error I am on the body getting is as follows:
Value of protocol type 'View' cannot conform to 'View'; only struct/enum/class types can conform to protocols
, which is due to the .sheet
modifier cause when I comment it out, the view works just fine...
推荐答案
只需移除闭包返回类型(从返回的内容中自动推断),即
Just remove closure return type (which is inferred automatically from returned content), i.e.
.sheet(item: $showSheet) { sheet in // << here !!
Text(sheet.rawValue)
}
这篇关于SwiftUI:有条件地显示不同的工作表项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!