Augusto
Augusto

Reputation: 4243

How implement "Next" and "Done" functions of UITextField on Swift4?

I have a formulary of login, with 3 fields and a button to login. I wants set a button in the keyboard do jump of UITextField to next when user ends write the content. Besides that, when user put text on last field, the button login is hidden behind keyboard! I tried choose the options on the attributes inspector, but I don't know how use this.

enter image description here

class ViewControllerAuthentication: UIViewController {

@IBOutlet weak var btEntrar: UIButton!
@IBOutlet weak var textPassword: UITextField!
@IBOutlet weak var textEmail: UITextField!
@IBOutlet weak var textURL: UITextField!

let alert = Alerta()

var url : String?
var email : String?
var password : String?

override func viewDidLoad() {
    self.btEntrar.addTarget(self, action: #selector(clickEntrar), for: .touchUpInside)

}

 @objc func clickEntrar(_ sender : UIButton) {
         // Do anything
     }

}

Upvotes: 2

Views: 41

Answers (1)

Krunal
Krunal

Reputation: 79776

You can do it, using UITextFieldDelegate, like...

class ViewControllerAuthentication: UIViewController, UITextFieldDelegate {


  @IBOutlet weak var textPassword: UITextField!
  @IBOutlet weak var textEmail: UITextField!
  @IBOutlet weak var textURL: UITextField!

    override func viewDidLoad() {

      textPassword.delegate = self
      textEmail.delegate = self
      textURL.delegate = self

      textURL.returnKeyType = .next
      textEmail.returnKeyType = .next
      textPassword.returnKeyType = .default // or .done

    }

    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        switch textField {

        case textURL:
            textEmail.becomeFirstResponder()

        case textEmail:
            textPassword.becomeFirstResponder()

        case textPassword:
            textField.resignFirstResponder()

        default:
            textField.resignFirstResponder()
        }

        return true
    }

}

I suggest IQKeyboardManager, if you don't want to handle each field manually.

Upvotes: 1

Related Questions