Darin Wilson Darin Wilson - 1 month ago 7
Swift Question

Trying to Hide UITextField on UISegmentedControl toggle

I'm trying to hide nameTextField when toggled on Login and make it show toggled on Register. I've been trying to figure it out myself, but here is what I've got. I have gotten it down to two errors and they're the same. Issue Navigator

lazy var loginRegisterSegmentControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Login", "Register"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.white
sc.selectedSegmentIndex = 1

switch sc.selectedSegmentIndex
{
case 0: nameTextField.isHidden = true
case 1: nameTextField.isHidden = false
default:
break;

sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged)
return sc

}
}

Answer
lazy var loginRegisterSegmentControl: UISegmentedControl = {
    let sc = UISegmentedControl(items: ["Login", "Register"])
    sc.translatesAutoresizingMaskIntoConstraints = false
    sc.tintColor = UIColor.white
    sc.selectedSegmentIndex = 1

    switch sc.selectedSegmentIndex
    {
    case 0: self.nameTextField.isHidden = true
    case 1: self.nameTextField.isHidden = false
    default:
        break; 

    sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged)
    return sc

    }
}()