KeyboardObserver 键盘事件处理开源项目

我要开发同款
匿名用户2016年01月04日
59阅读
开发技术Swift
所属分类键盘(Keyboard)、iOS代码库
授权协议MIT

作品详情

KeyboardObserver是为了处理不太复杂的键盘事件。

特性:

处理不太复杂的键盘事件。

不是使用NSNotification,而是使用event。

区别:

不用KeyboardObserver.swift

let keyboardNotifications = [    UIKeyboardWillShowNotification,    UIKeyboardWillHideNotification,    UIKeyboardWillChangeFrameNotification]override func viewDidLoad() {    super.viewDidLoad()}override func viewWillAppear(animated: Bool) {    super.viewWillAppear(animated)    keyboardNotifications.forEach {        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardEventNotified:", name: $0, object: nil)    }}override func viewWillDisappear(animated: Bool) {    super.viewWillDisappear(animated)    keyboardNotifications.forEach {        NSNotificationCenter.defaultCenter().removeObserver(self, name: $0, object: nil)    }}func keyboardEventNotified(notification: NSNotification) {    guard let userInfo = notification.userInfo else { return }    let keyboardFrameEnd = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()    let curve = UIViewAnimationOptions(rawValue: UInt(userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber))    let duration = NSTimeInterval(userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber)    let distance = UIScreen.mainScreen().bounds.height - keyboardFrameEnd.origin.y    let bottom = distance >= bottomLayoutGuide.length ? distance : bottomLayoutGuide.length    UIView.animateWithDuration(duration, delay: 0.0, options: [curve], animations:        { [weak self] () -> Void in            self?.textView.contentInset.bottom = bottom            self?.textView.scrollIndicatorInsets.bottom = bottom        } , completion: nil)}

用KeyboardObserver.swift

let keyboard = KeyboardObserver()override func viewDidLoad() {    super.viewDidLoad()    keyboard.observe { [weak self] (event) -> Void in        guard let s = self else { return }        switch event.type {        case .WillShow, .WillHide, .WillChangeFrame:            let distance = UIScreen.mainScreen().bounds.height - event.keyboardFrameEnd.origin.y            let bottom = distance >= s.bottomLayoutGuide.length ? distance : s.bottomLayoutGuide.length            UIView.animateWithDuration(event.duration, delay: 0.0, options: [event.curve], animations:                { [weak self] () -> Void in                    self?.textView.contentInset.bottom = bottom                    self?.textView.scrollIndicatorInsets.bottom = bottom                } , completion: nil)        default:            break        }    }}
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论