美文网首页
收回键盘的两种方式

收回键盘的两种方式

作者: 陆志均 | 来源:发表于2018-03-29 09:25 被阅读10次

    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()
        }
    
    }
    

    相关文章

      网友评论

          本文标题:收回键盘的两种方式

          本文链接:https://www.haomeiwen.com/subject/wuopcftx.html