Loading

SwiftUI State,Binding 状态管理

代码

//
//  ContentView.swift
//  SwiftUIState
//
//  Created by CHEN Hao on 2024/5/8.
//

import SwiftUI

struct ContentView: View {
    @State private var isPlaying = false
    @State private var clickNumber1 = 0
    @State private var clickNumber2 = 0
    @State private var clickNumber3 = 0

    var body: some View {
        Text("\(clickNumber1+clickNumber2+clickNumber3)") // "\(variables)",文本差插值
            .font(.system(size: 100, weight: .bold, design: .rounded))

        HStack {
            CounterButton(counter: $clickNumber1, color: .red) // $variables 传值, 可以理解成父传子
            CounterButton(counter: $clickNumber2, color: .orange)
            CounterButton(counter: $clickNumber3, color: .green)
        }
    }
}

struct CounterButton: View {
    @Binding var counter: Int // 接受值
    var color: Color

    var body: some View {
        Button {
            counter += 1
        } label: {
            Circle().frame(width: 50, height: 50)
                .foregroundStyle(color)
                .overlay {
                    Text("\(counter)")
                        .font(.system(size: 20, weight: .bold, design: .rounded))
                        .foregroundStyle(.white)
                }
        }
    }
}

#Preview {
    ContentView()
}

效果

posted @ 2024-05-08 21:59  ThankCAT  阅读(26)  评论(0编辑  收藏  举报