收回键盘的两种方式

1.利用 UITextFieldDelegate 协议 委托 textFieldShouldReturn
2.点击空白处让键盘消失

import UIKit

// 添加协议 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
    }
    
    // 点击空白处的方法
    @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)
        
        // 注册点击事件
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:))))
        
        // UIGestureRecognizer类用于手势识别,它的子类有主要有六个分别是:
        // UITapGestureRecognizer(轻击一下)
        // UIPinchGestureRecognizer(两指控制的缩放)
        // UIRotationGestureRecognizer(旋转)
        // UISwipeGestureRecognizer(滑动,快速移动)
        // UIPanGestureRecognizer(拖移,慢慢移动)
        // UILongPressGestureRecognizer(长按)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

推荐阅读更多精彩内容