Home > Software engineering >  How to make toggle switch always ON in swift?
How to make toggle switch always ON in swift?

Time:03-25

I want to make the state of toggle switch to ON always, even if user tries to make it OFF, it should not change. I tried to use .isUserInterstionEnabled = .false, but that didn't work. Can somebody help me on this? Thank you in advance

CodePudding user response:

Try using toggle.isEnabled = false

CodePudding user response:

There are two ways that I see you can achieve what you want.

  1. Disable it, using the modifier .disabled() (the user will see it slightly faded):
struct Example: View {
    
    @State private var isOn = true
    
    var body: some View {
        VStack {
            Toggle("Text of toggle", isOn: $isOn)
                .disabled(true)
        }
    }
}
  1. Force it to go back to on, using the modifier .onChange(of:):
struct Example: View {
    
    @State private var isOn = true
    
    var body: some View {
        VStack {
            Toggle("Text of toggle", isOn: $isOn)
        }
        .onChange(of: isOn) { _ in
            isOn = true
        }
    }
}

CodePudding user response:

1.Make the switch outlet in the view controller.

2.Create IBAction of switch and set-:

"self.swithCtrl.setOn(true, animated: false)"

User will try to disable it but it will remain enable.

  • Related