if(user.reserved == "yes") {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.green)
            
            Text("\(user.name)").foregroundColor(.green)
        }
    } else if (user.reserved == "no"){
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.red)
            
            Text("\(user.name)").foregroundColor(.red)
        }
    } else if (user.reserved == "waiting") {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.orange)
            
            Text("\(user.name)").foregroundColor(.orange)
        }
    }

'''

我有这个代码,我想根据用户说是或否来更改文本 colored颜色 的外观.我try 在if语句中创建一个类似"var color:color"的变量,但它一直说它不符合视图.我怎样才能有效地生成条件代码,而不是一次又一次地复制过go 的每一件事?

推荐答案

可以使用基于用户reserved属性返回Color的计算(computed)属性:

struct User {
    var reserved : String
    var name : String
}

struct ContentView: View {
    @State private var user = User(reserved: "waiting", name: "Bob")
    
    var colorForReserved : Color {
        switch user.reserved {
        case "yes":
            return .green
        case "no":
            return .red
        case "waiting":
            return .orange
        default:
            return .black
        }
    }
    
    var body: some View {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark")
            Text(user.name)
        }
        .foregroundColor(colorForReserved)
    }
}

Note that you can avoid the 100 if you changed 101 to an 102 rather than a 103

Swift相关问答推荐

SwiftData:线程1:&Quot;NSFetchRequest找不到实体名称';提醒&q;的NSEntityDescription

NSWindow中以编程方式创建的TextField快捷方式与SwiftUI

我正在try 通过代码设置节中页眉和页脚的高度,但它不起作用

从任务中打印

对实例方法appendInterpolation的调用没有完全匹配

在SwiftUI中如何预览嵌套的ScrollView,以避免触发可刷新修饰符

除法中如果除以完全因数需要更长时间吗?

如何在闭包中使用构造 await sync

仅当 boolean 为真时才实现方法(application:didReceiveRemoteNotification)

PassthroughSubject 的 AsyncPublisher 值属性未生成所有值

Swift Combine:如何在保留发布者结果顺序的同时进行收集?

MacOS KIND 是如何实现的

如何从数据中读取以空结尾的字符串?

Swift:创建用于调用 C 函数的指针数组

持久化字符串列表属性 RealmSwift

Alamofire 会自动存储 cookie 吗?

你如何在 UIBarItem 中使用 setTitleTextAttributes:forState?

来自 ObservableObject 的绑定值

在情节提要中设置的 UITableViewCell 的恢复 ID 和标识符有什么区别

为什么枚举具有计算(computed)属性但在 Swift 中没有存储属性?