新项目迭代中有个类似短信或QQ微信输入框随键盘推出的UI需求。
按照常用方法有两种:
1.注册通知动态获取键盘高度
2.自定义UITextField的inputView
下面是亲测流畅有效的通知监测获取键盘高度法:
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//添加通知
[self registerForKeyboardNotifications];
}
添加两个通知,UIKeyboardWillShowNotification,当键盘即将出现的时候,实现自定义带输入框的视图或其他UI控件的添加,UIKeyboardWillHideNotification,键盘即将隐藏的时候实现输入框移动到下沉到底部
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
}
在实现键盘即将出现方法的时候注意,此方法每次会走两遍,所以创建其他控件时要避免重复创建添加多次:
- (void) keyboardWasShown:(NSNotification *) notif
{
NSDictionary *info = [notif userInfo];
NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
NSLog(@"keyBoardheight = :%f", keyboardSize.height);
[UIView animateWithDuration:0.25 animations:^{
CGRect rect = self.footerView.frame;
rect.origin.y = ScreenHeight-keyboardSize.height-49- self.separateView.bottom - 20;
self.footerView.frame = rect;
} completion:^(BOOL finished) {
nil;
}];
//可避免重复创建添加
if (!_translucenceView) {
_translucenceView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-keyboardSize.height-49)];
_translucenceView.backgroundColor = COLOR(0, 0, 0, 0.5);
}
}
可把视图下移的动画写在下面方法里,textField通过调用resignFirstResponder方法即可调动此方法。
- (void) keyboardWasHidden:(NSNotification *) notif
{
[UIView animateWithDuration:0.25 animations:^{
CGRect frame = self.footerView.frame;
frame.origin.y = ScreenHeight - 49 - self.separateView.bottom - 20;
self.footerView.frame = frame;
}];
[self.translucenceView removeFromSuperview];
self.translucenceView = nil;
}
OK,亲测收缩流畅的输入框就成了。