SwiftUI 中通过Toggle实现单选框和复选框效果

效果如下

import SwiftUI

struct ContentView: View {
    @State private var bo = false
    var body: some View {
        Toggle("开关", isOn: $bo)
            .toggleStyle(CheckBoxToggleStyle(shape: .square))
    }
    struct CheckBoxToggleStyle: ToggleStyle{
        enum CheckBoxShape: String{
            case circle
            case square
        }
        let shape : CheckBoxShape
        init(shape: CheckBoxShape = .circle){
            self.shape = shape
        }
        //configuration中包含isOn和label
        func makeBody(configuration: Configuration) -> some View {
            let systemName:String = configuration.isOn ? "checkmark.\(shape.rawValue).fill" : shape.rawValue
            Button(action: {
                configuration.isOn.toggle()
            }) {
                configuration.label
                Image(systemName: systemName)
                    .resizable()
                    .frame(width: 30, height: 30)
            }
            

        }
    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
posted @ 2021-07-20 11:35  我不爱吃鱼  阅读(1044)  评论(0编辑  收藏  举报
Live2D