键盘出现时缩小UIWebView

时间:2014-01-14 21:15:49

标签: ios objective-c uiwebview

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

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

对此有任何指导意见。

先谢谢。

2 个答案:

答案 0 :(得分: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];
}

如果是其他子视图,您应该稍微更改此代码(添加其他子视图的帧更改)

答案 1 :(得分: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
}