Swift 版本: 2.利用 NSNotificationCenter實現鍵盤彈出時頁面自適應
阿新 • • 發佈:2018-12-30
在前面的一個小 Demo 裡, 我們知道了怎麼用UISearchController實現一個本地的搜素引擎, 現在讓我們繼續來看看接下來的Demo.
1.介面佈局
使用自動佈局給UI控制元件進行約束
獲取Bottom屬性
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.最終的效果
好了, 這次我們就講到這裡, 下次我們繼續~~