SwiftUI 中通過Toggle實現單選框和複選框效果
阿新 • • 發佈:2021-07-20
效果如下
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() } }