上代码:
键盘回收弹出
主要是取出系统通知里的参数用到动画展示中
// 注册通知
func registNotification(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHid:"), name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillChange:"), name: UITextViewTextDidChangeNotification, object: nil)
}
// 将要出现
func keyboardWillShow(notification:NSNotification){
// 通知传参
let userInfo = notification.userInfo
// 取出键盘bounds
let keyBoardBounds = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
// 时间
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
// 动画模式
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16))
// 偏移量
let deltaY = keyBoardBounds.size.height
// 动画
let animations:(() -> Void) = {
self.transform = CGAffineTransformMakeTranslation(0,-deltaY)
}
// 判断是否需要动画
if duration > 0 {
UIView.animateWithDuration(duration, delay: 0, options:options, animations: animations, completion: nil)
}else{
animations()
}
}
// 将要收起
func keyboardWillHid(notification:NSNotification){
let userInfo = notification.userInfo
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations:(() -> Void) = {
self.transform = CGAffineTransformIdentity
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16))
UIView.animateWithDuration(duration, delay: 0, options:options, animations: animations, completion: nil)
}else{
animations()
}
}
textView换行
主要是通过当前textView.contentSize的高度计算出textView改变后的frame赋值给textView
// 将要改变
func keyboardWillChange(notification:NSNotification){
let contentSize = self.textView.contentSize
if contentSize.height > 140{
return;
}
var selfframe = self.frame
// 计算textView距离上下X2的距离 再加上textView的高
var selfHeight = (self.textView.superview?.frame.origin.y)! * 2 + contentSize.height
if selfHeight <= selfDefultHight {
selfHeight = selfDefultHight
}
let selfOriginY = selfframe.origin.y - (selfHeight - selfframe.size.height)
selfframe.origin.y = selfOriginY;
selfframe.size.height = selfHeight;
self.frame = selfframe;
self.textView.frame = CGRectMake(1, 1, textViewW, selfHeight-20);
self.backgroundView.frame = CGRectMake(10, 10, textViewW+2, selfHeight-18);
}
背景那一条线是一个底部的黑色View