【问题标题】:How to create like a multiple value Boolean in SwiftUI?如何在 SwiftUI 中创建多值布尔值?
【发布时间】:2020-03-19 13:34:56
【问题描述】:

假设我有一个 SwiftUI 组件,我希望它根据我选择的参数改变颜色:

Component(colorValue: "1")
Component(colorValue: "2")
Component(colorValue: "3")

colorValue: 1 会将我的组件的颜色更改为红色,2 更改为绿色,3 更改为蓝色。

当我在项目开始时只有 2 种颜色时,我在组件中使用了布尔值:

Rectangle().fill(Color(colorValue ? "red" : "blue"))

但是现在我有多项选择,如何通过检查 colorValue String 的值来实现颜色变化?

提前致谢!

【问题讨论】:

    标签: if-statement conditional-statements swiftui modifier


    【解决方案1】:

    只使用一个函数

    func getColorValue() -> Color {
      if colorValue == 1 { return .red }
      // and so on
    }
    
    Rectangle().fill(Color(getColorValue()))
    

    【讨论】:

      猜你喜欢
      • 2010-09-25
      • 2021-10-17
      • 1970-01-01
      • 2019-04-27
      • 2014-02-20
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      相关资源
      最近更新 更多