当前位置: 首页 > 操作系统 > 手机系统 > 正文

IOS中解决Keyboard遮盖输入的办法

时间:2014-03-18 csdn RannieR

一般来说,键盘遮挡主要有这么几种情况,一个是遮住UITextView,还有就是遮住UITextField,一 般来说,比较推荐在UIScrollView或者UITableView里加入textfield的控件。但是有时也许难免。

在UITextView中

这个在苹果官方文档中的项目中给出了做法,首先是注册观察者监听 UIKeyboardWillShow和WillHide事件

- (void)viewWillAppear:(BOOL)animated  
{  
    [super viewWillAppear:animated];  
          
    [[NSNotificationCenter defaultCenter] addObserver:self  
                                             selector:@selector(keyboardWillShow:)  
                                                 name:UIKeyboardWillShowNotification  
                                               object:nil];  
    [[NSNotificationCenter defaultCenter] addObserver:self  
                                             selector:@selector(keyboardWillHide:)  
                                                 name:UIKeyboardWillHideNotification  
                                               object:nil];  
}

实现自定义的方法

- (void)keyboardWillShow:(NSNotification *)aNotification 

 
{  
    NSDictionary *userInfo = [aNotification userInfo];  
          
    CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] 

CGRectValue];  
    NSTimeInterval animationDuration = [[userInfo 

objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];  
          
    CGRect newFrame = self.view.frame;  
    newFrame.size.height -= keyboardRect.size.height;  
          
    [UIView beginAnimations:@"ResizeTextView" context:nil];  
    [UIView setAnimationDuration:animationDuration];  
          
    self.view.frame = newFrame;  
          
    [UIView commitAnimations];  
}

获取键盘显示的信息,然后根据信息对view的frame进行调整,然后WillHide方法就跟上面相 同,只不过把高度新高度改成+= keyboardRect.size.height就可以了,最后,移除观察者:

- 

(void)viewDidDisappear:(BOOL)animated  
{  
    [super viewDidDisappear:animated];  
          
    [[NSNotificationCenter defaultCenter] removeObserver:self  
                                                    name:UIKeyboardWillHideNotification  
                                                  object:nil];  
    [[NSNotificationCenter defaultCenter] removeObserver:self  
                                                    name:UIKeyboardWillShowNotification  
                                                  object:nil];  
}