Swift 隐藏键盘

2016-09-09  本文已影响0人  HeeeJianBo

各种萌新在日常 iOS 的 App 开发中经常会在编辑 UITextfeild UITextView 遇到键盘隐藏的问题:

  1. 键盘弹出后的收回
  2. 键盘遮挡住 UITextfeildUITextView

所以,在此分享能适应绝大多数的场景 一行代码隐藏键盘 的方法。

引入代码段

在任何 .swift 文件中引入以下代码

import UIKit

private var kUIViewFrame = "kk_UIViewFrame"
extension UIViewController {
    
    func setUpKeyboardAutoHidden() {
        let notficaCenter = NSNotificationCenter.defaultCenter()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(UIViewController.touchedHiddenKeyBoard))
        
        objc_setAssociatedObject(self, &kUIViewFrame, NSValue(CGRect: self.view.frame), .OBJC_ASSOCIATION_RETAIN)
        
        // 添加tap手势,收起键盘
        notficaCenter.addObserverForName(
            UIKeyboardWillShowNotification,
            object: nil,
            queue: NSOperationQueue.mainQueue()) { (notification) -> Void in
                self.view.addGestureRecognizer(tapGesture)
        }
        
        // 移除Tap手势,避免和App中的UIResponder链冲突
        notficaCenter.addObserverForName(
            UIKeyboardWillHideNotification,
            object: nil,
            queue: NSOperationQueue.mainQueue()){ (notification) -> Void in
                self.view.removeGestureRecognizer(tapGesture)
        }
        
        // 键盘遮挡处理
        notficaCenter.addObserverForName(
            UIKeyboardWillChangeFrameNotification,
            object: nil,
            queue: NSOperationQueue.mainQueue()) { (notification) -> Void in
                let usrInfo = notification.userInfo!
                let keyboardRect = usrInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue
                if let respView = self.view.findFirstResponder {
                    
                    let convertRect = self.view.convertRect(respView.frame, fromView: respView.superview)
                    let offset = convertRect.origin.y + convertRect.height - keyboardRect.origin.y
                    var orignRect = objc_getAssociatedObject(self, &kUIViewFrame).CGRectValue
                    
                    if offset > 0 {
                        orignRect.origin.y = -offset
                    }
                    
                    UIView.animateWithDuration(0.3, animations: { () -> Void in
                        self.view.frame = orignRect
                    })
                }
        }
    }
    
    //取消所有的响应者
    func touchedHiddenKeyBoard() {
        self.view.endEditing(true)
    }
}

使用

在引入以上代码段后,在需要配置键盘隐藏的 UIViewController 中添加如下代码:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 配置键盘隐藏
        setUpKeyboardAutoHidden()
    }
}

文章出自我的个人博客, 如需转载, 请注明来源!

上一篇下一篇

猜你喜欢

热点阅读