Set Toggle Color in Swiftui

Set Toggle color in SwiftUI

SwiftUI 3.0

Using tint

A new modifier was introduced that can also change the Toggle color:

Toggle(isOn: $isToggleOn) {
Text("Red")
Image(systemName: "paintpalette")
}
.tint(.red)

Toggle(isOn: $isToggleOn) {
Text("Orange")
Image(systemName: "paintpalette")
}
.tint(.orange)

Toggle Tint Color

SwiftUI 2.0

Using SwitchToggleStyle

You can now set a tint color for the on position only in SwiftUI 2.0:

Toggle(isOn: $isToggleOn) {
Text("Red")
Image(systemName: "paintpalette")
}
.toggleStyle(SwitchToggleStyle(tint: Color.red))

Toggle(isOn: $isToggleOn) {
Text("Orange")
Image(systemName: "paintpalette")
}
.toggleStyle(SwitchToggleStyle(tint: Color.orange))

Toggle Tint Color

SwiftUI 1.0

Using ToggleStyle

I created a new ToggleStyle to change the three colors of the Toggle (on color, off color, and the thumb).

struct ColoredToggleStyle: ToggleStyle {
var label = ""
var onColor = Color(UIColor.green)
var offColor = Color(UIColor.systemGray5)
var thumbColor = Color.white

func makeBody(configuration: Self.Configuration) -> some View {
HStack {
Text(label)
Spacer()
Button(action: { configuration.isOn.toggle() } )
{
RoundedRectangle(cornerRadius: 16, style: .circular)
.fill(configuration.isOn ? onColor : offColor)
.frame(width: 50, height: 29)
.overlay(
Circle()
.fill(thumbColor)
.shadow(radius: 1, x: 0, y: 1)
.padding(1.5)
.offset(x: configuration.isOn ? 10 : -10))
.animation(Animation.easeInOut(duration: 0.1))
}
}
.font(.title)
.padding(.horizontal)
}
}

Examples of Use

Toggle("", isOn: $toggleState)
.toggleStyle(
ColoredToggleStyle(label: "My Colored Toggle",
onColor: .green,
offColor: .red,
thumbColor: Color(UIColor.systemTeal)))

Toggle("", isOn: $toggleState2)
.toggleStyle(
ColoredToggleStyle(label: "My Colored Toggle",
onColor: .purple))

From the SwiftUI Book

Toggle Example

How to change body background color with if in SwiftUI

You just need to embed your VStack inside a ZStack, where the back layer is a color that changes every time isOnLight changes.

Like this:

struct Example: View {

@State private var isOnLight: Bool = false
@State private var color: Color = .white

var body: some View {
ZStack {
color
.ignoresSafeArea()

VStack {
Toggle(isOn: $isOnLight) {
Text("Switch")
.font(.title)
.foregroundColor(.gray)
}
}
.padding()
}
.onChange(of: isOnLight) { value in
if value {
color = .yellow
} else {
color = .white
}
}
}
}

SwiftUI toggle active / inactive line color on custom TextField

If I understood correctly it is enough to use onEditingChanged, like below

var body: some View {
VStack {
TextField("12345678", text: $phoneNumber, onEditingChanged: {
self.isActive = $0 // << here !!
}).keyboardType(.phonePad)
Divider()
.padding(.horizontal)
.frame(height: 1)
.background(isActive ? Color.red : Color.gray)
}
}

SwiftUI how to set the button style toggle taking the whole highlighted width

try the following code, to make the buttons expand the highlighted width so each of them takes half of the available screen width.

HStack {
SUITextToggle(label: "roundUp", isOn: stateUp) { _ in
viewModel.toggleRoundingType(.up)
}
SUITextToggle(label: "roundDown", isOn: stateDown) { _ in
viewModel.toggleRoundingType(.down)
}
}


public struct SUITextToggle: View {
@State var isOn: Bool

private var binding: Binding<Bool> {
Binding<Bool> {
return isOn
} set: { newValue in
isOn = newValue
onChange(newValue)
}
}

let label: String
let onChange: (Bool) -> Void

init(label: String, isOn: Bool, onChange: @escaping (Bool) -> Void) {
self.label = label
self.isOn = isOn
self.onChange = onChange
}
public var body: some View {
Toggle(isOn: binding) {
Text(label).frame(maxWidth: .infinity).contentShape(Rectangle()) // <-- here
}
.toggleStyle(.button)
}
}

SwiftUI: How can I set a color to .foregroundColor() by using a String? i.e. green -- Color.green

Use

Color(lernset.color)

It only works if the String value of lernset.color is defined as a Color Set in Assets

This

Color.lernset.color

or

Color.green

References a static variable. You would need something like

extension Color{
static let yourColor: Color = Color("nameHere")
}

Then you can call

Color.yourColor

With "nameHere" being the name of a Color Set

Change background color of multiple buttons on SwiftUI

You need to have one variable didTap for each Button. This can be achieved by moving the button to a separate view.

You can create this view:

struct MyButton: View {

@State private var didTap = false // This will change the color

let myRow: String // I'm assuming it's a String, otherwise use the correct type

@Binding var isNight: Bool // This will change the variable in the parent view
@Binding var variableTitle: String // This will change the variable in the parent view (always assuming it's a String)

var body: some View {
Button{
didTap.toggle()
variableTitle = myRow
isNight.toggle()
} label:{
ULD(title: myRow, textColor: .black, backgroundColor: didTap ? .red : .green)
}
}
}

Then, in your parent view just call it as per the following example. Remember that isNight and variableTitle must both be a @State variable in the parent view.

ForEach(allWords, id: \.self) { myRow in
MyButton(myRow: myRow, isNight: $isNight, variableTitle: $variableTitle)
}

How to change state of SwiftUI Toggle externally

You're on the right track by creating a custom Binding with a set function that performs your side effect. But instead of using a State, create a custom Binding that directly modifies the enabled property of your ObservableObject. Example:

import PlaygroundSupport
import SwiftUI

class MyModel: ObservableObject {
@Published var enabled: Bool = false
@Published var sideEffectCount: Int = 0
}

struct RootView: View {
@EnvironmentObject var model: MyModel

var body: some View {
List {
Text("Side effect count: \(model.sideEffectCount)")

Button("Set to false programmatically") {
model.enabled = false
}

Button("Set to true programmatically") {
model.enabled = true
}

Toggle("Toggle without side effect", isOn: $model.enabled)

Toggle("Toggle WITH side effect", isOn: Binding(
get: { model.enabled },
set: { newValue in
withAnimation {
if newValue {
model.sideEffectCount += 1
}
model.enabled = newValue
}
}
))
}
}
}

PlaygroundPage.current.setLiveView(
RootView()
.environmentObject(MyModel())
)


Related Topics



Leave a reply



Submit