在前面的一个小 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