SwiftUI 使用 ToggleStyle 自定义 Toggle的代码演示

14 min read

以下是一个使用 ToggleStyle 自定义 Toggle 的示例代码:

struct CustomToggleStyle: ToggleStyle {
    func makeBody(configuration: Configuration) -> some View {
        HStack {
            configuration.label
            Spacer()
            Button(action: {
                configuration.isOn.toggle()
            }) {
                Image(systemName: configuration.isOn ? "checkmark.square" : "square")
                    .foregroundColor(configuration.isOn ? .green : .red)
            }
        }
    }
}

struct ContentView: View {
    @State private var toggleValue = false
    
    var body: some View {
        Toggle("Custom Toggle", isOn: $toggleValue)
            .toggleStyle(CustomToggleStyle())
    }
}

这里创建了一个名为 CustomToggleStyle 的自定义 ToggleStyle,并实现了 makeBody(configuration:) 方法。该方法返回一个包含一个标签和一个按钮的 HStack。该按钮会在切换时更新状态。

在 ContentView 中,将 Toggle 视图和 toggleValue 绑定,并使用 toggleStyle(_:) 方法将自定义样式应用于 Toggle。 运行此代码将显示一个带有自定义样式的 Toggle。当开关切换时,按钮上将显示相应的状态,并且颜色也会更改。