form1.cn
Make a little progress every day

Swift3.0中点击屏幕收回键盘

23th of February 2017 Swift Swift+IOS 2914

点击UITextField以外的区域,实际是点击了当前View,当前View捕获点击事件,可它不会传递该事件

这种简单可用办法:addGestureRecognizer

class ViewController: UIViewController { 
    
    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var password: UITextField!  
      
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册点击事件
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
        
    } 
  
    //点击空白处关闭键盘方法
    func handleTap(sender: UITapGestureRecognizer) {
        if sender.state == .ended {
            print("收回键盘")
            self.username.resignFirstResponder()//username放弃第一响应者
            self.password.resignFirstResponder()//password放弃第一响应者
        }
        sender.cancelsTouchesInView = false
    } 
  
}



其它事件

UIGestureRecognizer //类用于手势识别,它的子类有主要有六个分别是:
UITapGestureRecognizer //(轻击一下)
UIPinchGestureRecognizer //(两指控制的缩放)
UIRotationGestureRecognizer //(旋转)
UISwipeGestureRecognizer //(滑动,快速移动)
UIPanGestureRecognizer //(拖移,慢慢移动)
UILongPressGestureRecognizer //(长按)