标签:
总结了以下几种方式,欢迎补充
3,为TextField绑定Did End On Exit事件
一、点击编辑区域以外的地方时关闭(空白处区域绑定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();
}
}
二、点击编辑区域以外的地方时关闭(重写touchesEnded)
只需要在ViewController里重写touchesEnded方法
//触摸事件,当一个或多个手指离开屏幕时触发
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
name.resignFirstResponder();
}
三、点击软键盘右下角的Done/Go/Next...关闭键盘(为TextField绑定Did End On Exit事件)
选择Main.storyboard中的Text Field,按住control拖拉的方式为其绑定Did End On Exit事件

@IBAction func DoneCloseKeyBoard(sender: AnyObject) {
name.resignFirstResponder();
}
标签:
原文地址:http://www.cnblogs.com/Sunlimi/p/swift-closekeyboard.html