總結了以下幾種方式,歡迎補充
3,為TextField綁定Did End On Exit事件
1,點擊編輯區域以外的地方時關閉(空白處區域綁定Touch Up Inside事件
新建一個項目,打開Main.storyboard,添加一個Text Field,與ViewController建立連接,然后點擊空白處,在右邊窗口修改Custom Class 的class改為UIControl

然后為UIControl綁定Touch Up Inside事件(只有改為UIControl后才能綁定事件)

ViewController:
import UIKit
class ViewController: UIViewController {
@IBOutlet var name: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func CloseKeyBoard(sender: AnyObject) {
name.resignFirstResponder();
}
}
2,點擊編輯區域以外的地方時關閉(重寫touchesEnded)
只需要在ViewController里重寫touchesEnded方法
//觸摸事件,當一個或多個手指離開屏幕時觸發
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
name.resignFirstResponder();
}
3,點擊軟鍵盤右下角的Done/Go/Next...關閉鍵盤(為TextField綁定Did End On Exit事件)
選擇Main.storyboard中的Text Field,按住control拖拉的方式為其綁定Did End On Exit事件

@IBAction func DoneCloseKeyBoard(sender: AnyObject) {
name.resignFirstResponder();
}
