【问题标题】:How to: Use conditional custom background views for background modifier?如何:使用条件自定义背景视图作为背景修饰符?
【发布时间】: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


    【解决方案1】:

    视图必须是一种类型,这是可能的解决方案

    Image(systemName: "circle.fill")
        .background(Group {
           if self.buttonPressed { BackgroundView1() }
             else { BackgroundView2() }
        }) 
    

    替代方案是,如果视图很简单(否则可能是性能问题),

        Image(systemName: "circle.fill")
            .background(self.buttonPressed ? AnyView(BackgroundView1()) : AnyView(BackgroundView2()))
    

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多