键盘监听的使用

在实际开发中监听键盘弹出,让某一个View或者是TextField跟随键盘移动,这样的情况非常普遍。在这里自己总结一下,帮助自己复习,另外也起到一个备忘的作用吧。
方案如下,可能不是最好,但是在没有发现更好的方法前就用这个吧。

第一步:创建添加监听事件方法
func addKeyboardObserver() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
    }

创建监听方法,在设置监听的位置调用,当然可以在viewDidload或者willDidload中直接添加也可以,我个人的习惯是,能写成方法的就尽量写成方法,以后复制粘贴比较方便

第二步:创建删除监听事件方法
func removeKeyboardObserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

添加完之后,就立刻写一个删除监听的方法与其对应起来

第三步:实现监听中声明的方法
func keyboardWillShow(sender: NSNotification) {
        guard let userInfo = sender.userInfo else {
            return
        }
        guard let keyboardSize = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue else {
            return
        }
        guard let keyboardDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue else {
            return
        }
        guard let keyboardCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey]?.intValue else {
            return
        }
        searchBarConstraint.constant = keyboardSize.height
        UIView.animateWithDuration(keyboardDuration, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(keyboardCurve)), animations: {
            self.view.layoutIfNeeded()
            }, completion: nil)
    }

    func keyboardWillHide(sender: NSNotification) {
        guard let userInfo = sender.userInfo else {
            return
        }
        guard let keyboardDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue else {
            return
        }
        guard let keyboardCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey]?.intValue else {
            return
        }
        searchBarConstraint.constant = 0
        UIView.animateWithDuration(keyboardDuration, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(keyboardCurve)), animations: {
            self.view.layoutIfNeeded()
            }, completion: nil)
    }

从userInfo 中提取到键盘的高度,运动的时间,运动的模式。然后设置layout的属性,这里设置的是从storyboard中拖线过来的约束,根据userInfo中的属性来设置约束,并动画改变,这样一来就可以让某个View跟随键盘上下滚动了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值