iOS TextField收取键盘的方法

2017-02-17 17:15

今天闲下来,没有其他的事情,整理了一下几种TextField收取键盘的方法,其实也非常的简单

1.通过注册第一响应者,myTextField?.resignFirstResponder(),代码如下:

class ViewController: UIViewController {
    var myTextField:UITextField?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        myTextField=UITextField(frame: CGRect(x: 100, y: 200, width: 100, height: 50))
        myTextField?.placeholder="Context"
        //弹出键盘
        myTextField?.becomeFirstResponder();
        self.view.addSubview(myTextField!)
    }
    //点击屏幕的时候,就会相应改事件
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //收回键盘
        myTextField?.resignFirstResponder()
    }
2.取消当前页面的编辑状态

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //收回键盘
        self.view.endEditing(false)
    }
3.设置返回按键

class ViewController: UIViewController,UITextFieldDelegate, UITextViewDelegate{
    var myTextField:UITextField?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        myTextField=UITextField(frame: CGRect(x: 100, y: 200, width: 100, height: 50))
        myTextField?.placeholder="Context"
        //弹出键盘
        myTextField?.becomeFirstResponder();
        myTextField?.delegate=self
        myTextField?.returnKeyType=UIReturnKeyType.done
        self.view.addSubview(myTextField!)
    }
    //点击Do的时候,就会相应改事件
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        myTextField?.resignFirstResponder()
        return true
    }