-5

I have an app with two switch controls to hide or show some textfield depending on their state on or off.

The problem is the first switch seems to control the second one.

If the first switch is off, the second switch is off also. I would like them to work independently from each other. Any advice?

Thanks guys

@IBAction func switchP(_ sender: UISwitch) {
    if (sender.isOn == true) {
        textFieldP.isHidden = false
    } else {
        textFieldP.isHidden = true
    }
}

@IBAction func switchT(_ sender: UISwitch) {
    if (sender.isOn == true) {
        textFieldT.isHidden = false
    } else {
        textFieldT.isHidden = true
    }
}
picciano
  • 22,341
  • 9
  • 69
  • 82
John
  • 1
  • 3
  • 1
    show your IBOutlet IBAction connections, make sure that they are connected properly – Scriptable Apr 11 '18 at 13:15
  • 1
    Your Action connections in the storyboard are configured incorrectly. – matt Apr 11 '18 at 13:15
  • 3
    Swift != Switch – matt Apr 11 '18 at 13:18
  • 1
    BTW, `sender.isOn` is a `Bool`, so there's no need to test it against `true`. Simply `if sender.isOn {`. And, if that is all your code is doing, then `textFieldP.isHidden = !sender.isOn` is all you need. – vacawama Apr 11 '18 at 13:19
  • Note: `== true` is redundant, and also you don't need the brackets. The proper Swift form is like this: `if sender.isOn {` – Eric Aya Apr 11 '18 at 13:47
  • Sorry for the confusion, you are right matt it is switch not swift. thanks to does data for the new edit of the question. And thanks to vacawama to simplify the code, i changed it. Thanks to scriptable and matt you are right my storyboard was wrong, they were both under the same IBAction – John Apr 11 '18 at 13:48

2 Answers2

1

First, replace

if (sender.isOn == true) {
    textFieldP.isHidden = false
} else {
    textFieldP.isHidden = true
}

by a simple single line:

textFieldP.isHidden = !sender.isOn

Second, use Connections Inspector (right panel, the arrow in the circle) and make sure your Referencing Outlets are not mixed or duplicated under the same IBAction.

Zyntx
  • 659
  • 6
  • 19
0

Other than specifying the .isHidden = true using if/else statements, you should use an opposite property reference which is a lot nicer way of doing it.

@IBAction var switchP: [UIView] {
didSet {
    textFieldP.forEach {
      $0.isHidden = true
      }
   }
}

And to change based on a click:

@IBAction func switchP(_ sender: UISwitch) {
    UIView.animate(withDuration: 0.2) {
        self.switchP.forEach {
            $0.isHidden = !$0.isHidden
        }
    }
}

That's the best I can generically answer without seeing all of your code.

Super_Simon
  • 1,250
  • 8
  • 25