viewdidload里面,加了一个[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];
通知,然后取出键盘的高度。因为在5.0以后,键盘高度是不固定的。中文是252,英文的是216。Printing description of notification:
NSConcreteNotification 0xc55a130 {name = UIKeyboardWillShowNotification; userInfo = {
UIKeyboardAnimationCurveUserInfoKey = 0;
UIKeyboardAnimationDurationUserInfoKey = "0.25";
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 216}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 588}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 372}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 216}}";
UIKeyboardFrameChangedByUserInteraction = 0;
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 264}, {320, 216}}";
}}
如果你的输入文本框是在UI的最下面,类似于短信输入框那种,
只要将self.view 移动一个键盘的距离216或者252就可以了。等键盘落下的时候再移回来。
如下:代码来自:这里
-(void)keyboardWillShow:(NSNotification *)notification
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardBounds;
[keyboardBoundsValue getValue:&keyboardBounds];
NSInteger offset =self.view.frame.size.height-keyboardBounds.origin.y+64.0;
CGRect listFrame = CGRectMake(0, -offset, self.view.frame.size.width,self.view.frame.size.height);
NSLog(@"offset is %d",offset);
[UIView beginAnimations:@"anim" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3];
//处理移动事件,将各视图设置最终要达到的状态
self.view.frame=listFrame;
[UIView commitAnimations];
}
}
但如果界面布局比较的复杂。有几处要输出文本的地方,这个时候你需要判断出是哪个textField 是当前输入框-focus。
for ( UIView *childViewin view.subviews ) {
if ( [childView respondsToSelector:@selector(isFirstResponder)] && [childViewisFirstResponder] ) return childView;
}比如UItableView的 用户名密码输入框,因为tableView是
UIScrollView的子view,继承
UIScrollView的属性,利用上面代码找到当前focus的textField后,将textField的父view--也就是tableView 移到 可视的那片区域(self.view-去掉keyboardd区域)---
setContentOffset:Offsetanimated:YES
就可以了。
具体实现:
未完待续!