UIKit应用 - Swift 版本: 2.利用 NSNotificationCenter实现键盘弹出时页面自适应

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


1.界面布局

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

获取Bottom属性
1

2


2.代码实现

获取Bottom属性

    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!

定义监听方法

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

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

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

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

        // 3.3.获取动画的时间
        var animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval

        // 3.4.获取改变的高度
        var changeInHeight = (CGRectGetHeight(keyboardFrame) + 5) * (show ? 1 : -1)
        // 3.5.使用动画
        UIView.animateWithDuration(animationDurarion, animations: { () -> Void in
            self.bottomConstraint.constant += changeInHeight
        })
    }

重写viewWillDisappear方法

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

重写单击的方法

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        // 结束编辑状态
        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.最终的效果

1


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

posted @ 2015-05-17 20:14  背着吉他去流浪  阅读(465)  评论(0编辑  收藏  举报