如何在Swift中手动启用/禁用键盘返回键?

时间:2016-02-11 21:20:13

标签: ios swift keyboard uitextfield

  

这个问题不会与这些问题重复:

     

我有两个TextFields

@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!
  • textField1下一步按钮,如返回键;

  • textField2 Go 按钮,如返回键;

textField1

textField2

如果两个TextField都不为空,我想启用第二个TextField的 Go 按钮。

我尝试将someTextField.enablesReturnKeyAutomaticallyTextFieldDelegate一起使用,但无效。

感谢您的帮助。

1 个答案:

答案 0 :(得分:7)

下方:textField2只要textField1为空即被停用。如果后者非空,我们会启用textField2,但仅当Go非空(通过textField2属性)时才启用.enablesReturnKeyAutomatically按钮,

/* 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
    }
}

运行如下:

enter image description here