问题
This question is not duplicated from these:
How to disable/enable the return key in a UITextField?
How to enable or disable the keyboard return key
Enable and Disable Keyboard return key on demand in iOS
I have two TextFields
.
@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!
textField1
has the Next button like the Return Key;textField2
has the Go button like the Return Key;
textField1
textField2
I would like to enable the Go button of the second TextField just if both TextFields are not empty.
I tried to use someTextField.enablesReturnKeyAutomatically
with TextFieldDelegate
, but did not work.
Thank you for help.
回答1:
Below: textField2
is disabled as long as textField1
is empty. If the latter is non-empty, we enable textField2
, but enable the Go
button only if textField2
is non-empty (via .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
}
}
Runs as follows:
来源:https://stackoverflow.com/questions/35350243/how-could-i-enable-disable-keyboard-return-key-manually-in-swift