最近做的项目中,有一个类似微信的聊天发送框,屏幕底端有一个输入框用textView来做,当textView成为第一响应者的时候它的Y值随着键盘高度的改变而改变,保证textView紧贴着键盘,但又不会被键盘挡住。
先来看一下关于键盘的一些通知代理
//键盘显示发出通知
UIKeyboardWillShowNotification
UIKeyboardDidShowNotification
//键盘隐藏发出通知
UIKeyboardWillHideNotification
UIKeyboardDidHideNotification
// 键盘的frame发生改变时发出的通知(位置和尺寸)
UIKeyboardWillChangeFrameNotification
UIKeyboardDidChangeFrameNotification
注册通知来观察键盘的显示和隐藏
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
接着就是监听方法
#pragma 监听方法
- (void)keyboardWillShow:(NSNotification *)notify {//键盘弹起改变TextView位置
//拿到键盘尺寸
CGRect rect = [notif.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//取得键盘高度
CGFloat keyBoardHeight = rect.size.height;
//TextView的y = 整个屏幕高度 - 键盘高度 - TextView的高度
[UIView animateWithDuration: [notif.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
TextView.y = KSCREENHEIGHT -keyBoardHeight - TextView.height;
}];
}
- (void)keyboardWillHide:(NSNotification *)notification {//键盘回收改变TextView的位置
//TextView的y = 整个屏幕高度 - TextView的高度
[UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
TextView.y = KSCREENHEIGHT - TextView.height;
}];
}
网友评论