1. 程式人生 > >Swift 版本: 2.利用 NSNotificationCenter實現鍵盤彈出時頁面自適應

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

好了, 這次我們就講到這裡, 下次我們繼續~~