Skeyboard.swift
struct SKeyBoard {
// 注冊鍵盤出現(xiàn)
static func registerKeyBoardShow(target: UIViewController) {
NSNotificationCenter.defaultCenter().addObserver(target, selector: "keyboardWillShowNotification:", name: UIKeyboardWillShowNotification, object: nil)
}
// 注冊鍵盤隱藏
static func registerKeyBoardHide(target: UIViewController) {
NSNotificationCenter.defaultCenter().addObserver(target, selector: "keyboardWillHideNotification:", name: UIKeyboardWillHideNotification, object: nil)
}
// 移除鍵盤出現(xiàn)通知
static func removeKeyboardNotifications(target: UIViewController) {
NSNotificationCenter.defaultCenter().removeObserver(target, name: UIKeyboardWillShowNotification, object: nil)
}
// 移除鍵盤隱藏通知
static func removeKeyboardHideNotifications(target: UIViewController) {
NSNotificationCenter.defaultCenter().removeObserver(target, name: UIKeyboardWillHideNotification, object: nil)
}
// 返回鍵盤高度
static func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
// 返回鍵盤上拉動畫持續(xù)時間
static func getKeyBoardDuration(notification: NSNotification) -> Double {
let userInfo = notification.userInfo
let keyboardDuration = userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
return keyboardDuration
}
// 返回鍵盤動畫曲線
static func getKeyBoardAnimationCurve(notification: NSNotification) -> NSObject {
let userInfo = notification.userInfo
let keyboardTranstionAnimationCurve = userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSValue
return keyboardTranstionAnimationCurve
}
}
使用
1.注冊通知
SKeyBoard.registerKeyBoardShow(self)
SKeyBoard.registerKeyBoardHide(self)
2.必須實現(xiàn)以下2個方法,否則程序會崩潰
func keyboardWillShowNotification(notification:NSNotification){
let rect = SKeyBoard.getKeyboardHeight(notification)
self.textView.contentInset = UIEdgeInsetsMake(0, 0, rect, 0)
}
func keyboardWillHideNotification(notification: NSNotification) {
self.textView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
}