在前面的一個小 Demo 裏, 咱們知道了怎麼用UISearchController實現一個本地的搜素引擎, 如今讓咱們繼續來看看接下來的Demo.markdown
使用自動佈局給UI控件進行約束
app
獲取Bottom屬性
ide
獲取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方法ui
// 重寫 viewWillDisappear 方法
override func viewWillDisappear(animated: Bool) {
// 1.刪除鍵盤顯示時的觀察者
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
// 2.刪除鍵盤隱藏時的觀察者
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
重寫單擊的方法spa
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// 結束編輯狀態
self.view.endEditing(true)
}
在viewDidLoad中實現code
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)
}
好了, 此次咱們就講到這裏, 下次咱們繼續~~server