Created
November 28, 2024 15:10
-
-
Save Codelaby/f6e74e3cac202296460bbc09110d5c8f to your computer and use it in GitHub Desktop.
How to set Mixed toggle in SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct MixedToggleStyle: ToggleStyle { | |
| func makeBody(configuration: Configuration) -> some View { | |
| HStack { | |
| configuration.label | |
| Spacer() | |
| Button { | |
| configuration.isOn.toggle() | |
| } label: { | |
| // Image( | |
| // systemName: configuration.isMixed | |
| // ? "minus.circle.fill" : configuration.isOn | |
| // ? "checkmark.circle.fill" : "circle") | |
| iconAndColor(for: configuration) | |
| .imageScale(.large) | |
| } | |
| .controlSize(.large) | |
| } | |
| } | |
| private func iconAndColor(for configuration: Configuration) -> some View { | |
| let icon: String | |
| let color: Color | |
| switch (configuration.isMixed, configuration.isOn) { | |
| case (true, _): | |
| icon = "minus.circle.fill" | |
| color = Color.secondary | |
| case (false, true): | |
| icon = "checkmark.circle.fill" | |
| color = Color.accentColor | |
| case (false, false): | |
| icon = "circle" | |
| color = Color.secondary | |
| } | |
| return Image(systemName: icon).foregroundStyle(color) | |
| } | |
| } | |
| #Preview { | |
| struct UserList: Identifiable { | |
| var id: UUID = .init() | |
| var name: String | |
| var isFollowing = false | |
| } | |
| struct PreviewWrapper: View { | |
| @State var lists = [ | |
| UserList(name: "fatbobman (东坡肘子)", isFollowing: false), | |
| UserList(name: "Itsuki", isFollowing: false), | |
| UserList(name: "Kavsoft", isFollowing: false), | |
| UserList(name: "Sucodee", isFollowing: false), | |
| UserList(name: "Codelaby", isFollowing: false), | |
| ] | |
| var body: some View { | |
| Form { | |
| Section { | |
| ForEach($lists) { $list in | |
| Toggle(list.name, isOn: $list.isFollowing) | |
| .id($list.id) | |
| // .toggleStyle(SwitchToggleStyle(tint: .blue)) | |
| } | |
| } header: { | |
| Toggle("Follow favorite creators", sources: $lists, isOn: \.isFollowing) | |
| .toggleStyle(MixedToggleStyle()) | |
| } | |
| } | |
| } | |
| } | |
| return VStack { | |
| PreviewWrapper() | |
| CreditsView() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment