Swift - Add Show Password button

1

I have a text field, I have already included an image on the right side, clicking on this would like to reveal the password, however, I am not able to reach this result. The current code is:

import UIKit

class LoginViewController: UIViewController {

    @IBOutlet weak var usuarioOuEmail: UITextField!
    @IBOutlet weak var senha: UITextField!
    @IBOutlet weak var mostrar: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        let imageView = UIImageView();
        imageView.image = UIImage(named: "logo.png")
        imageView.frame = CGRectMake(0, 0, 23, 23);
        senha.rightView = imageView
        senha.rightViewMode = UITextFieldViewMode.Always
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

How do I click another image to trigger the image?

    
asked by anonymous 27.09.2015 / 22:08

2 answers

1

I got something close to what I want using the code:

import UIKit

class LoginViewController: UIViewController {

    @IBOutlet weak var usuarioOuEmail: UITextField!
    @IBOutlet weak var senha: UITextField!
    @IBOutlet weak var mostrarOcultar: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: "mostrarOcultarSenha")
        mostrarOcultar.addGestureRecognizer(tap)
        mostrarOcultar.userInteractionEnabled = true
    }

    func mostrarOcultarSenha()
    {
        if senha.secureTextEntry == false
        {
            mostrarOcultar.image = UIImage(named: "botao_ocultar.png")
            senha.secureTextEntry = true
        }
        else
        {
            mostrarOcultar.image = UIImage(named: "botao_mostrar")
            senha.secureTextEntry = false
        }
    }
//... 
}

But the problem is that when I click on the UIImageView responsible for revealing the password the same is shown with another size and font style, the cursor keeps blinking away from the font because of the formatting. Look:

    
28.09.2015 / 15:53
0

To capture touches on ImageView you can add a TapGestureRecognizer . Example:

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    imageView.userInteractionEnabled = true
    let gestureRecognizer = UITapGestureRecognizer(target: self, action:"handleImageTap:")
    imageView.addGestureRecognizer(gestureRecognizer)

}

func handleImageTap(gestureRecognizer: UIGestureRecognizer) {
   senha.text = "senhaUltraSecreta"
}
    
28.09.2015 / 03:52