各種萌新在日常 iOS 的 App 開發(fā)中經(jīng)常會在編輯 UITextfeild UITextView 遇到鍵盤隱藏的問題:
- 鍵盤彈出后的收回
- 鍵盤遮擋住
UITextfeild或UITextView
所以,在此分享能適應(yīng)絕大多數(shù)的場景 一行代碼隱藏鍵盤 的方法。
引入代碼段
在任何 .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
})
}
}
}
//取消所有的響應(yīng)者
func touchedHiddenKeyBoard() {
self.view.endEditing(true)
}
}
使用
在引入以上代碼段后,在需要配置鍵盤隱藏的 UIViewController 中添加如下代碼:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 配置鍵盤隱藏
setUpKeyboardAutoHidden()
}
}