SwiftUI 中的条件格式

Pra*_*azz 2 swift swiftui

我想格式化文本。

Text("Hello")
.foregroundColor(self.amount > 20 ? .blue : .white) 
Run Code Online (Sandbox Code Playgroud)

你会如何添加另一个条件:

if self.amount > 100 and self.amount > 200 
Run Code Online (Sandbox Code Playgroud)

等等?

Bib*_*cob 9

不能向三元?运算符添加超过 2 个参数。但你可以这样做:

var body: some View {
    Text("Hello")
        .foregroundColor(amount > 100 ? .red : amount > 20 ? .blue : .white)
}
Run Code Online (Sandbox Code Playgroud)

或者你将不得不使用if else像这样的普通语句:

var body: some View {
    if self.amount > 200 {
        return Text("Hello")
            .foregroundColor(.blue)
    } else if self.amount > 100 {
        return Text("Hello")
            .foregroundColor(.white)
    } else {
        return Text("Hello")
            .foregroundColor(.black)
    }
}
Run Code Online (Sandbox Code Playgroud)


Sco*_*tyA 5

我尝试了上面的解决方案,并根据评论中@Sajjon 提供的答案取得了成功。我想将其重新发布在这里作为一个有用的替代解决方案。

\n
var textColor: Color { \n   if amount <= 20 { \n      return .white \n   } else if amount < 40 { \n      return .blue \n   } else { \n      return .red \n   } \n} \n
Run Code Online (Sandbox Code Playgroud)\n

然后在身体里

\n
Text(\xe2\x80\x9cHello\xe2\x80\x9d)\n   .foreGroundColor(self.textColor)\n
Run Code Online (Sandbox Code Playgroud)\n