swift - 基于非二进制数据/条件修改 SwiftUI View ?

标签 swift switch-statement boolean swiftui

问题:我有一个相当大的 SwiftUI View ,它根据我的模型数据添加国家/地区代码。我的感觉是我应该提取一个 subview ,然后传入国家/地区代码,然后使用 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)
        }
    }
}

最佳答案

这是更干净的方法:

  1. 仅显示文本一次 - 使用函数获取颜色
Text("Bilbo").foregroundColor(self.getColor(index))
  • 创建 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 作为默认情况,因为它必须存在

    关于swift - 基于非二进制数据/条件修改 SwiftUI View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62792475/

    相关文章:

    java - Java 开关的奇怪输出

    c++ - 使用带有 bitset 的 initializer_list

    swift - ReactiveSwift Action observeResult 没有像应该的那样返回失败

    ios - 在 UNNotification 我得到的 userInfo 值与 UNNotificationRequest Swift 中的设置值不同

    ios - 如何处理 iOS 中的 Firebase 数据库错误? #AskFirebase

    C switch case 的结果真的很奇怪

    swift - 试图理解 swift 子类中的 super 属性

    javascript - 按住 Shift 键的同时按下箭头键

    python - 比较python nlp中的集合

    c++ - 使用动态 boolean 数组的问题