Conditional/条件运算符, Ternary/三目运算符 的使用

1. Conditional 条件运算符的使用

  1.1 实现

/// 条件语句
struct ConditionalBootcamp: View {
    @State var showCircle: Bool = false
    @State var showRectangle: Bool = false
    @State var isLoading: Bool = false
    
    var body: some View {
        //conditionalView1
        conditionalView2
    }
    
    /// 方式二
    var conditionalView2: some View{
        VStack(spacing: 20) {
            
            Button("Is Loading: \(isLoading.description)") {
                isLoading.toggle()
            }
            
            if isLoading{
                ProgressView()
            }
            Spacer()
        }
    }
    
    /// 方式一
    var conditionalView1: some View{
        VStack(spacing: 20) {
            Button("Circle Button: \(showCircle.description)") {
                showCircle.toggle()
            }
            Button("Rectangle Button: \(showRectangle.description)") {
                showRectangle.toggle()
            }
            if showCircle {
                Circle()
                    .frame(width: 100, height: 100)
            }
            if showRectangle{
                Rectangle()
                    .frame(width: 100, height: 100)
            }
            if showCircle && showRectangle{
                RoundedRectangle(cornerRadius: 25)
                    .frame(width: 200, height: 100)
            }
            Spacer()
        }
    }
}

  1.2 效果图:

    1) 方式一:

     2) 方式二:

2. Ternary 三目运算符的使用

  2.1 实现

/// 三目运算符
struct TernaryBootcamp: View {
    @State var isStartingState:Bool = false
    
    var body: some View {
        VStack{
            // 按钮
            Button("Button: \(isStartingState.description)") {
                isStartingState.toggle()
            }
            // 文本
            Text(isStartingState ? "Starting State" : "Ending State")
            // 圆角矩形
            RoundedRectangle(cornerRadius: isStartingState ? 25 : 0)
                .fill(isStartingState ? Color.red : Color.blue)
                .frame(width: isStartingState ? 200 : 50,
                       height: isStartingState ? 100 : 50)
            Spacer()
        }
    }
}

  2.2 效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hanyang Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值