Swift:UITextField在第一次点击时立即被解雇

时间:2017-02-04 13:31:20

标签: ios swift uitextfield

当我打开应用程序并单击UITextField时,它会在第一次单击时立即被解除。第一次没有点击视图外,它不会被解雇。

我使用了这个答案:Close iOS Keyboard by touching anywhere using Swift,用于在点击textField外部区域时解除textField的代码。代码:

class SettingsViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var textField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    textField.delegate = self
}


 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
}


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

    textField.resignFirstResponder()
    return false
}

1 个答案:

答案 0 :(得分:0)

从您的问题中想出,当有人点击视图而不是文本字段时,您想要关闭键盘。您可以覆盖视图控制器上开始的触摸:

import UIKit

class ViewController: UIViewController {

    // MARK: - Properties
    @IBOutlet weak var textField: UITextField!

    // MARK: - Actions
    // will resign any first repsonder on this view contorller
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }

    // MARK: - Lifecycle
    override func viewDidLoad() {
        textField.delegate = self
    }

}

extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return false
    }
}

而不必担心水龙头等。