How can I enable / disable the Return Key keyboard manually in Swift?

This question is not duplicated:

I have two TextFields .

 @IBOutlet weak var textField1: UITextField! @IBOutlet weak var textField2: UITextField! 
  • textField1 has a Next button, such as Return Key;

  • textField2 has a Go button such as Return Key;

textField1

textField2

I would like to enable the Go button of the second TextField only if both TextField are not empty.

I tried to use someTextField.enablesReturnKeyAutomatically with TextFieldDelegate but did not work.

Thank you for your help.

+5
source share
1 answer

Below: textField2 disabled while textField1 empty. If the latter is not empty, we textField2 , but textField2 Go button only if textField2 not empty (via the .enablesReturnKeyAutomatically property),

 /* ViewController.swift */ import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var textField1: UITextField! @IBOutlet weak var textField2: UITextField! override func viewDidLoad() { super.viewDidLoad() // text field delegates textField1.delegate = self textField2.delegate = self // set return key styles textField1.returnKeyType = UIReturnKeyType.Next textField2.returnKeyType = UIReturnKeyType.Go // only enable textField2 if textField1 is non-empty textField2.enabled = false // only enable 'go' key of textField2 if the field itself is non-empty textField2.enablesReturnKeyAutomatically = true } // UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField1.text?.isEmpty ?? true) { textField2.enabled = false textField.resignFirstResponder() } else if textField == textField1 { textField2.enabled = true textField2.becomeFirstResponder() } else { textField.resignFirstResponder() } return true } } 

It works as follows:

enter image description here

+5
source

Source: https://habr.com/ru/post/1242810/


All Articles