ios - 出现键盘时缩小 UIWebView

标签 ios objective-c uiwebview

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

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

感谢任何关于此的指导。

提前致谢。

最佳答案

要缩小 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];
}

如果有其他 subview ,您应该稍微更改此代码(添加其他 subview 的框架更改)

关于ios - 出现键盘时缩小 UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21124188/

相关文章:

objective-c - 为什么 Xcode 说它可能会泄漏?

ios - UIWebView 在关闭其父 View 时重新加载视频

ios - UIcollectionView 的约束

ios - iPad 上的 UIDatePicker 布局问题

objective-c - 如何提高从 url 加载图像的性能

iphone - iOS:在 iOS 中处理数据库的最佳方式是什么?

ios - 我如何知道什么时候已将某些内容粘贴到 UIWebView 中?

ios - UIWebView 和 Javascript 的内存泄漏

ios - 应用程序处于后台模式或强制停止 iOS 10 时未收到推送通知

ios - 重新创建过期推送证书配置文件的一般步骤是什么?