通常情况下,如何在修改器中使用三元操作符进行有条件的更改是很直接的。但是当我试图在两个自定义背景修改器的视图之间切换时,我得到了这个错误。如果你直接指定颜色作为备用视图,就不会出现这种情况。
错误,'?:'表达式中的结果值。'?:'表达式中的结果值的类型'BackgroundView1'和'BackgroundView2'不匹配。
import SwiftUI
struct TestView: View {
@State var buttonPressed = false
var body: some View {
Button(action: {self.buttonPressed.toggle()}) {
Image(systemName: "circle.fill")
.background(self.buttonPressed ? BackgroundView1() : BackgroundView2()) // Error
// .background(buttonPressed ? Color.red : Color.green)
}
}
}
struct BackgroundView1: View {
var body: some View {
Color.red
}
}
struct BackgroundView2: View {
var body: some View {
Color.green
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
视图必须是一个类型,这里是可能的解决方案
Image(systemName: "circle.fill")
.background(Group {
if self.buttonPressed { BackgroundView1() }
else { BackgroundView2() }
})
如果视图很简单,另一种情况是(否则可能会有性能问题)。
Image(systemName: "circle.fill")
.background(self.buttonPressed ? AnyView(BackgroundView1()) : AnyView(BackgroundView2()))