收回键盘的方法——swift笔记

0x00 简述

最近尝试用swift写ios应用时,发现苹果设备在输入完成后不能像android一样收回键盘,参考网上资料,整理出自己使用的两种能够收回键盘的方法。
注:基于swift2.2

0x01 return键收起

通过textview或者textfiled点击键盘return(中文下为换行)实现键盘收回。(下面以textfiled示例)

class ViewController: UIViewController, UITextFieldDelegate { // 添加protocol 
 @IBOutlet weak var textView: UITextField!
  override func viewDidLoad(){
    super.viewDidLoad()
    textView.delegate=self
   
}
//通过委托来实现  
//UITextField Delegate Method  
func textFieldShouldReturn(textField: UITextField) -> Bool {  
    textView.resignFirstResponder()  
    return true  
}     
0x02 点击屏幕收回

点击UITextField以外的区域收回屏幕键盘,使用method:addGestureRecognizer。

class AddDayReportViewController: UITableViewController {  
        
@IBOutlet weak var textView: UITextView!        
override func viewDidLoad() {  
    super.viewDidLoad()  
     
//注册点击事件
 view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ForthViewController.handleTap(_:))))
}    
func handleTap(sender: UITapGestureRecognizer) {
    if sender.state == .Ended {
        textView.resignFirstResponder()           
    }
    sender.cancelsTouchesInView = false
  }
}  
Updated At: Author:xmsec
Chief Water dispenser Manager of Lancet, delivering but striving.
Github
comments powered by Disqus