Wayne
Wayne

Reputation: 293

UIButton becomes not visible when changing image

When I use the following code the first time I press the button it works. When I press it again, the secure entry portion works but the button becomes visible. Although it is still there and still works. Any idea what I am doing wrong?

 @IBAction func showPasswordButtonPressed(_ sender: UIButton) {
    if passwordTextField.text != ""  {
            if passwordTextField.isSecureTextEntry == true {
                passwordTextField.isSecureTextEntry = false
                let btnImage = UIImage(named: "password-hide")
                passwordButton.setImage(btnImage, for: UIControlState.normal)
            } else  {
                passwordTextField.isSecureTextEntry = true
                let btnImage = UIImage(named: "password-show")
                passwordButton.setImage(btnImage, for: UIControlState.normal)
        }
    }
}

Upvotes: 0

Views: 55

Answers (1)

Ali Beadle
Ali Beadle

Reputation: 4516

UIImage will return nil if it cannot find the image. UIButton.setImage accepts an optional value, so will silently set a nil image if passed one.

Add a check to your code that the image is not nil before using it.

Upvotes: 1

Related Questions