Swift - Add button show password

Asked

Viewed 204 times

1

I have a text field, I have already been able to include an image on the right side, by clicking this I 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 on the image to fire another function?

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 it is shown with another size and font style, the cursor is flashing away from the font because of the formatting. Behold: inserir a descrição da imagem aqui

  • I did a test and had the same problem. From what I saw this is a bug to Uitextfield http://www.openradar.appspot.com/20345712

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"
}
  • I tried something similar, but it had no effect.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.