美文网首页我的Swift开发swift编程开发Swift项目相关
Swift 键盘显示与隐藏通知封装SKeyBoard

Swift 键盘显示与隐藏通知封装SKeyBoard

作者: 小黑Swift | 来源:发表于2016-02-29 23:32 被阅读1115次

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

    相关文章

      网友评论

      本文标题:Swift 键盘显示与隐藏通知封装SKeyBoard

      本文链接:https://www.haomeiwen.com/subject/ykigkttx.html