研究ios开发有段时间了,但是一直没有时间把所积累下的东西写出来分享,现在打算抽些时间把所学到的东西跟大家一一分享出来,让那些像我一样自学ios的童鞋们也少走些弯路。
开发中很多时候会遇到一些情况,很小的细节往往会弄的人不知道改怎么去处理。
在很多时候,当你在View上面点击一个UITextFiled的时候,弹出键盘会遮挡住输入框,你根本不知道自己在输入些什么,以前做这方面的处理的时候,是这样写的
-(void) viewUp:(UIVIew *) view
{
UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
CGPoint center = contentViewCenter;
center.y -= 50;
contentView.center = center;
[UIView commitAnimations];
}
只是将UITextFiled往上移动,输入完成之后,再将UITextFiled移动回来,但是当键盘出现中英文切换的时候,出现候选文字的时候,仍会造成遮挡,这该怎么解决呢?
以前在面试工作的时候,也碰到过类似的问题,当时我回答的就只是上面一个方法,结果面试官一笑置之,呵呵。
后来查了查文档,Apple早就做过像出现这种情况的时候的处理方法,就是在View加载的时候,注册2个NSNotification,这两个NSNotification分别为:KeyboardWillShow 和 KeyboardWillHide
注册方法如下:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
还需要在定义2个接收Notification的方法来响应事件:
- (void) keyboardWillShow:(NSNotification *) notification
{
NSDictionary *userInfo = [notification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
CGFloat keyboardTop = keyboardRect.origin.y;
CGRect newTextViewFrame =CGRectMake(0, keyboardTop-30, self.view.bounds.size.width, 30);
NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration;
[animationDurationValue getValue:&animationDuration];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
self.textView.frame = newTextViewFrame;
[UIView commitAnimations];
}
-(void)keyboardWillHidden:(NSNotification *) notification
{
//这里的操作跟Willshow一样,只需要将ViewFrame变下就OK
self.textView.frame = newTextViewFrame;
}
上面从notification里面读出来的信息中都包含有当前键盘弹出所涉及到的各种数据
NSDictionary *userInfo = [notification 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}}";
}
从这个NSDictionary的键就能很容易的知道这些数据所代表的意思,也能很块的找到你所需要的数据
微信公众平台已开通,加个关注呗。我们一起学习,一起进步
微信号:ios开发总汇
百度知道群:开发者俱乐部
![](https://img-my.csdn.net/uploads/201304/23/1366726039_2716.jpg)