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

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)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,250评论 4 61
  • 经常听到这样一句话:“女人,一定要矜持,这样别人才会珍惜你!” 这句话我赞同,不过我有另一种看法。 前天我上辅全,...
    girl挥着翅膀的女孩阅读 11,754评论 1 3
  • 忙了一天,很晚才到家。哄完孩子睡觉,再坐到书桌前,已近半夜。 今天的写作还没有,写点什么呢?脑中空无一物。 这两天...
    浅澜浅澜阅读 206评论 0 0