【问题标题】:How to use ternary operator with .foregroundStyle(primary: ShapeStyle, secondary: ShapeStyle)?如何将三元运算符与.foregroundStyle(primary:ShapeStyle,secondary:ShapeStyle)一起使用?
【发布时间】:2022-07-06 02:50:09
【问题描述】:

我正在尝试将两个参数传递给这个修饰符

.foregroundStyle(primary: ShapeStyle, secondary: ShapeStyle)

我希望主要参数基于 isTrue Bool 值,使用三元运算符,但出现错误。

工作与这个修饰符的一个参数版本:

.foregroundStyle(style: ShapeStyle)
.foregroundStyle((isTrue) ? Color.green : Color.secondary) // no error, works

但是不能使用这个修饰符的两个参数版本:

.foregroundStyle(primary: ShapeStyle, secondary: ShapeStyle)
.foregroundStyle((isTrue) ? Color.green, Color.blue : Color.secondary, Color.green) // Error: Expected ':' after '? ...' in ternary expression

为什么它不起作用?如何摆脱错误?

完整代码:

 Image(systemName: isTrue ? "clock.badge.checkmark.fill" : "clock.fill")
         .symbolRenderingMode(.palette)
         .foregroundStyle(Color.blue, Color.red) // no error, works
         .foregroundStyle((isTrue) ? Color.green, Color.blue : Color.secondary, Color.green) // Error: Expected ':' after '? ...' in ternary expression
         .foregroundStyle((isTrue) ? (Color.green, Color.red) : (Color.secondary, Color.white)) // Error: Expected ':' after '? ...' in ternary expression

【问题讨论】:

    标签: swift xcode swiftui conditional-operator


    【解决方案1】:

    用逗号分隔的两个参数:

     Image(systemName: isTrue ? "clock.badge.checkmark.fill" : "clock.fill")
             .symbolRenderingMode(.palette)
             .foregroundStyle((isTrue ? Color.green : Color.secondary), (isTrue ? Color.red : Color.white))
    

    【讨论】:

    • 谢谢。但是虽然这段代码没有给我任何错误,但它似乎忽略了第二个参数:(
    • 我的意思是它既不使用 Color.red 也不使用 Color.white。就像从不一样,无论 isTrue 值是什么。
    • @user14119170 它对我有用。当 isTrue 为真时,图标有红色时钟和绿色复选标记。当 isTrue 为 false 时,复选标记仅是辅助颜色,因为图标“clock.fill”在调色板渲染模式下只有一种颜色。
    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多