2014-01-14 41 views
0

在我的iPhone应用程序中,我有一个UIWebView,其上方有一个工具栏。底部的工具栏包含供用户输入一些文本的文本框。但是当我点击文本框时,键盘覆盖了屏幕的下半部分。当键盘出现时收缩UIWebView

我该如何让工具栏保持在webview上方和下方,但webview的高度会缩小以显示键盘?

对此的任何指导表示赞赏。

感谢先进。

回答

0

您可以实现UITextFieldDelegate在您的UIViewController并将UITextField代表值设置到您的控制器,然后在您的控制器中执行textFieldDidBeginEditingtextFieldDidEndEditing方法来检测何时编辑开始/结束。

- (void)textFieldDidBeginEditing:(UITextField *)textField{ 
    // in case you have more than one text fields in the same view 
    if(textField == self.YOUR_FIELD_NAME) 
     // change the web view height here, you can also animate it using UIView beginAnimations 
     CGRect frame = self.webView.frame; 
     frame.size.height = 200; 
     self.webView.frame = frame; 
} 


    - (void)textFieldDidEndEditing:(UITextField *)textField{ 
    // do the opposite here 
} 
2

要缩小webView的,你需要以下条件:

- (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) viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillDisappear:animated]; 

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; 
} 


- (void)keyboardWillShow:(NSNotification *)notification 
{  
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 
    keyboardFrame = [self.view convertRect:keyboardFrame fromView:self.view.window]; 

    NSTimeInterval keyboardAnimationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 
    UIViewAnimationOptions keyboardAnimationCurve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16; 

    CGFloat keyboardHeight = keyboardFrame.size.height; 

    [UIView animateWithDuration:keyboardAnimationDuration delay:0 options:keyboardAnimationCurve 
    animations:^{ 
      _webView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0) 
    } 
    completion:NULL]; 
} 


- (void)keyboardWillHide:(NSNotification *)notification 
{  
    NSTimeInterval keyboardAnimationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 
    UIViewAnimationOptions keyboardAnimationCurve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16; 

    [UIView animateWithDuration:keyboardAnimationDuration delay:0 options:keyboardAnimationCurve 
    animations:^{ 
      _webView.contentInset = UIEdgeInsetsZero; 
    } 
    completion:NULL]; 
} 

在额外的子视图的情况下,你应该稍微更改此代码(添加帧的其他子视图的变化)