微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

KeyboardObserver

程序名称:KeyboardObserver

授权协议: MIT

操作系统: iOS

开发语言: Swift

KeyboardObserver 介绍

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
        }
    }
}

KeyboardObserver 官网

https://github.com/morizotter/KeyboardObserver

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐