【发布时间】:2020-06-18 11:19:25
【问题描述】:
通常,如何使用三元运算符对修饰符进行有条件的更改是很简单的。但是当我尝试在背景修饰符的两个自定义视图之间切换时,我得到了这个错误。如果您不是这种情况,例如直接将颜色指定为备用视图。
错误:结果值在 '? :' 表达式有不匹配的类型 '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()
}
}
【问题讨论】:
标签: view background swiftui conditional-statements modifier