问题:我有一个相当大的 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)
}
}
}
最佳答案
这是更干净的方法:
- 仅显示文本一次 - 使用函数获取颜色
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/