Swift 键盘显示与隐藏通知封装SKeyBoard
2016-02-29 本文已影响1115人
小黑Swift
Skeyboard.swift
struct SKeyBoard {
// 注册键盘出现
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)
}
// 移除键盘出现通知
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
}
// 返回键盘上拉动画持续时间
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.必须实现以下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)
}