5.利用 NSNotificationCenter实现键盘弹出时页面自适应

在前面的一个小 Demo 里, 我们知道了怎么用UISearchController实现一个本地的搜素引擎, 现在让我们继续来看看接下来的Demo.

PS: 已更新到Swift 2.0, 支持Xcode7, iOS9


1.界面布局

使用自动布局给UI控件进行约束
1

获取Bottom属性
2

3


2.代码实现

获取Bottom属性

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

定义监听方法

    // 3.当键盘开始显示的时候调用 
    func keyboardWillShow(notification:NSNotification) {
        adjustingHeight(true, notification: notification)
    } 

    // 4.当键盘消失的时候调用
    func keyboardWillHide(notification:NSNotification) { 
        adjustingHeight(false, notification: notification) 
    } 

    // 5.设置键盘的属性 
    func adjustingHeight(show:Bool, notification:NSNotification) { 
    // 5.1.在字典中获取通知信息
    var userInfo = notification.userInfo! 

    // 5.2.获取键盘的Frame
    let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()

    // 5.3.获取动画时间 
    let animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval

    // 5.4.设置高度
    let changeInHeight = (CGRectGetHeight(keyboardFrame) + 5) * (show ? 1 : -1)

    // 5.5.使用动画
    UIView.animateWithDuration(animationDurarion, animations: { () -> Void in
        self.bottomConstraint.constant += changeInHeight })
     }

重写viewWillDisappear方法

// 6.重写 viewWillDisappear 方法 
override func viewWillDisappear(animated: Bool) { 
    // 6.1.删除键盘显示时的观察者 
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) 

// 6.2.删除键盘隐藏时的观察者 
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) 
}

重写单击的方法

// 7.重写点击事件 
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    // 7.1结束编辑状态 
    self.view.endEditing(true) 
}

在viewDidLoad中实现

    override func viewDidLoad() { 
        super.viewDidLoad() 

            // 1.添加键盘显示时的观察者
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)

            // 2.添加键盘消失时的观察者
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
    }

3.最终的效果

0


好了, 这次我们就讲到这里, 下次我们继续~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值