【问题标题】:Modifying SwiftUI Views based on non-binary data / conditions?根据非二进制数据/条件修改 SwiftUI 视图?
【发布时间】:2020-07-08 10:14:43
【问题描述】:

问题:我有一个相当大的 SwiftUI 视图,它根据我的模型数据添加了国家/地区代码。我的感觉是我应该提取一个子视图,然后将国家代码传入,然后使用switch,但我只是想检查一下我没有遗漏任何东西并使这变得太复杂。

SwiftUI 有一个非常好的方法来处理基于 Bool 的两个可能选项,这很好,因为它修改了单个 View

struct TestbedView_2: View {
    var isRed: Bool
    var body: some View {
        Text("Bilbo").foregroundColor(isRed ? Color.red : Color.blue)
    }
}

另一方面,如果您的模型呈现非二元选择,您可以使用switch 语句。但是,这会根据选择的情况返回一个独立的View,从而导致重复代码。

struct TestbedView_3: View {
    var index: Int
    var body: some View {
        switch(index) {
            case 1:
                Text("Bilbo").foregroundColor(Color.red)
            case 2:
                Text("Bilbo").foregroundColor(Color.green)
            default:
                Text("Bilbo").foregroundColor(Color.blue)
        }
    }
}

【问题讨论】:

  • 我认为这是一个简化的例子。你会展示更多真实的代码/你试图实现的部分,替代品可能取决于输入吗?

标签: swift switch-statement boolean swiftui


【解决方案1】:

这是更干净的方法:

  1. 仅显示一次文本 - 使用函数获取颜色
Text("Bilbo").foregroundColor(self.getColor(index))
  1. 创建 getColor 函数
private func getColor(_ index : Int) -> Color {        
    switch index {
    case 1: return Color.red
    case 2: return Color.green
    case 3: return Color.blue
    default: return Color.clear
    }
}

注意:我在 switch 语句中使用 Color.clear 作为默认情况,因为它必须存在

【讨论】:

  • 感谢您的回复,这是我在当前代码中采用的一个选项。我几乎希望 SwiftUI 2.0 能够以某种方式打开修饰符,而不是切换视图。我认为在这个阶段使用自定义辅助函数可能是最好的选择。非常感谢先生。
猜你喜欢
  • 2021-10-31
  • 2018-11-29
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多