UITextView被键盘遮挡的处理

这个应该是一个通用的任务了吧,键盘弹出来的时候,UITextView(或者UITextField)会被遮挡。 
解决的办法就不是很能通用了。 
1. 如果有UIScrollView做父view的话只需要滚动到合适的位置即可。 
2. 如果没有UIScrollView的话,可以恰当的临时调整一下UITextView的高度,使得最下面一行的输入也能被看到。 

下面只对第二种情况说明一下要点: 
我的做法是创建一个UITextView的派生类,这样可以方便重用。 
(不派生类也是可以的,原理一样。) 
注册2个Notification消息,分别是UIKeyboardDidShowNotification和UIKeyboardWillHideNotification 

表示键盘已经弹出来和键盘要消失的时候发送。

- (void) registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

 

消息的处理

 

- (void) keyboardWasShow:(NSNotification *) notification {
    //取得键盘frame,注意,因为键盘是window的层面弹出来的,所以其frame坐标也是对应window窗口的
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGPoint endOrigin = endRect.origin;
    
    NSLog(@"keyboard frame = %@",NSStringFromCGRect(endRect));
    //把键盘的frame坐标转换到与UITextView一致的父view上来
    endOrigin = [self.view convertPoint:endOrigin fromView:[UIApplication sharedApplication].keyWindow];
    NSLog(@"endOrigin = %@",NSStringFromCGPoint(endOrigin));
    
    //调整inputView的位置
    CGFloat inputView_Y = self.view.frame.size.height - endRect.size.height - self.inputView.frame.size.height;
    
    [UIView beginAnimations:nil context:nil];
    self.inputView.frame = CGRectMake(self.inputView.frame.origin.x, inputView_Y, self.inputView.frame.size.width, self.inputView.frame.size.height);
    [UIView commitAnimations];
    
}

- (void) keyboardWillBeHidden:(NSNotification *) notification {
    [UIView beginAnimations:nil context:nil];
    self.inputView.frame = _inputViewOriginalFrame;
    [UIView commitAnimations];
}

 

原文:http://my.oschina.net/dourgulf/blog/80723

 

 

posted @ 2013-11-29 10:56  Dadada胖纸er  阅读(1189)  评论(0编辑  收藏  举报