1.在viewdidload中,注册如下监听:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
2. 实现对应的监听触发方法:
func keyboardWillShow(note:NSNotification){
var userInfo:NSDictionary = note.userInfo!
var aValue:NSValue = userInfo.objectForKey("UIKeyboardFrameEndUserInfoKey") as! NSValue
var keyboardRect:CGRect = aValue.CGRectValue()
keyboardRect = self.view.convertRect(keyboardRect, fromView: nil)
var keyboardTop:CGFloat = keyboardRect.origin.y
var newTextViewFrame:CGRect = self.view.bounds
newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y
var animationDurationValue:NSValue = userInfo.objectForKey("UIKeyboardAnimationDurationUserInfoKey") as! NSValue
var animationDuration:NSTimeInterval? = 0.5
animationDurationValue.getValue(&animationDuration)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(animationDuration!)
self._chatView.frame = newTextViewFrame
UIView.commitAnimations()
}
func keyboardWillHide(note:NSNotification){
var userInfo:NSDictionary = note.userInfo!
var animationDurationValue:NSValue = userInfo.objectForKey("UIKeyboardAnimationDurationUserInfoKey") as! NSValue
var animationDuration:NSTimeInterval? = 0.5
animationDurationValue.getValue(&animationDuration)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(animationDuration!)
self._chatView.frame = self.view.bounds;
UIView.commitAnimations()
}
3.界面退出时,卸载监听,在
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}