skip to Main Content

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

3

Answers


  1. Try using toggle.isEnabled = false

    Login or Signup to reply.
  2. 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
            }
        }
    }
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search