英文:
Change thumb tint color of Toggle in SwiftUI
问题
有thumbTintColor
属性在UISwitch
(UIKit)。在SwiftUI的Toggle
中,相当于这个属性是什么?
英文:
There's thumbTintColor
property in UISwitch
(UIKit). What is the equivalent of this property in SwiftUI's Toggle
?
答案1
得分: 1
From this article:
> There is no way to change the tint color of Toggle from SwiftUI, but we can use UIAppearance API from UIKit to set the tint color for all UISwitch instances across the app.
So there is no direct way to do so. However, in your View
, you can easily set this globally with an init
:
struct MyToggleView: View {
init() {
//Replace with your desired color
UISwitch.appearance().onTintColor = .orange
}
//... (Rest of your view here)
}
Or, as the article suggests, you can go all the way and set up a full-on ToggleStyle
. See my example below, which alters the example from the docs so that you can give it a custom color:
struct ChecklistToggleStyle: ToggleStyle {
var color: Color
func makeBody(configuration: Configuration) -> some View {
Button {
configuration.isOn.toggle()
} label: {
HStack {
Image(systemName: configuration.isOn
? "checkmark.circle.fill"
: "circle")
configuration.label
}
}
.tint(color) //<<< Here!
.buttonStyle(.borderless)
}
}
And you can use it like this:
struct ContentView: View {
@State var toggleIsOn = false
var body: some View {
Toggle("Example", isOn: $toggleIsOn)
.toggleStyle(ChecklistToggleStyle(color: .blue)) //<<< HERE! The name of the custom style you created
}
}
英文:
From this article:
> There is no way to change the tint color of Toggle from SwiftUI, but we can use UIAppearance API from UIKit to set the tint color for all UISwitch instances across the app.
So there is no direct way to do so. However, in your View
, you can easily set this globally with an init
:
struct MyToggleView: View {
init() {
//Replace with your desired color
UISwitch.appearance().onTintColor = .orange
}
//... (Rest of your view here)
}
Or, as the article suggests, you can go all the way and set up a full-on ToggleStyle
. See my example below, which alters the example from the docs so that you can give it a custom color:
struct ChecklistToggleStyle: ToggleStyle {
var color: Color
func makeBody(configuration: Configuration) -> some View {
Button {
configuration.isOn.toggle()
} label: {
HStack {
Image(systemName: configuration.isOn
? "checkmark.circle.fill"
: "circle")
configuration.label
}
}
.tint(color) //<<< Here!
.buttonStyle(.borderless)
}
}
And you can use it like this:
struct ContentView: View {
@State var toggleIsOn = false
var body: some View {
Toggle("Example", isOn: $toggleIsOn)
.toggleStyle(ChecklistToggleStyle(color: .blue)) //<<< HERE! The name of the custom style you created
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论