1.利用 UITextFieldDelegate 協(xié)議 委托 textFieldShouldReturn
2.點(diǎn)擊空白處讓鍵盤消失
import UIKit
// 添加協(xié)議 UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {
let textField = UITextField(frame: CGRect(x: 100, y: 40, width: 120, height: 30))
// 委托方法
func textFieldShouldReturn(_ textFiled: UITextField) -> Bool {
textFiled.resignFirstResponder()
print(textFiled.text ?? "empty")
return true
}
// 點(diǎn)擊空白處的方法
@objc func handleTap(_ sender: UITapGestureRecognizer) {
if sender.state == .ended {
print("收回鍵盤")
self.view.endEditing(true)
}
sender.cancelsTouchesInView = false
}
override func viewDidLoad() {
super.viewDidLoad()
textField.borderStyle = UITextBorderStyle.roundedRect
textField.placeholder = "Email"
textField.autocorrectionType = UITextAutocorrectionType.no
textField.returnKeyType = UIReturnKeyType.done
textField.clearButtonMode = UITextFieldViewMode.whileEditing
textField.keyboardType = UIKeyboardType.emailAddress
textField.keyboardAppearance = UIKeyboardAppearance.default
textField.delegate = self
self.view.addSubview(textField)
// 注冊點(diǎn)擊事件
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:))))
// UIGestureRecognizer類用于手勢識別,它的子類有主要有六個分別是:
// UITapGestureRecognizer(輕擊一下)
// UIPinchGestureRecognizer(兩指控制的縮放)
// UIRotationGestureRecognizer(旋轉(zhuǎn))
// UISwipeGestureRecognizer(滑動啼染,快速移動)
// UIPanGestureRecognizer(拖移宴合,慢慢移動)
// UILongPressGestureRecognizer(長按)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}