当键盘出现时,我的 UIWebView 向上移动,而当键盘消失时,webview 不会回到其先前的位置。我已经检查了键盘出现之前和之后的 webview 的位置,或者关闭。令人惊讶的是,webview 的框架没有改变。但是我之前和之后看到的情况大不相同。
- 在键盘出现之前:
- 当键盘出现时,webview 上移
- 当键盘关闭时,webview 不会向下移动
到目前为止,我所做的是应用我从其他人那里学到的以下技术:
1)观察键盘通知,然后适当调整
2) 更改meta标签,同样在meta标签中添加“height=device-height”
3) 改变webview的属性:
_webView.contentMode = UIViewContentModeScaleAspectFit; _webView.scalesPageToFit = YES; _webView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
但是,以上所有这些建议都不起作用。你能帮帮我吗?
注:我用的是iOS7,XCODE 5
最佳答案
UIWebView
中有一个UIScrollView
来管理比屏幕大的内容。当您调整 UIScrollView
的高度时,它通常会影响它的滚动位置。当您使用键盘缩小高度时,它会导致内容向上滚动以保持文本字段可见(通过修改 contentOffset
),但是当您扩展高度时,它只会在底部显示更多内容,而不会' 将 contentOffset
改回原始值。
有很多方法可以解决这个问题,每个创建可编辑文本的人都会在某个时候处理它。这些年来我用过很多,我敢肯定可能还有更好的我什至没见过。
我最后的做法是修改 UIScrollView
的 contentInset
并保存原来的 contentOffset
这样我就可以重新填充稍后再说。
设置你的通知
[[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 *)notification {
NSDictionary *userInfo = [notification userInfo];
CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGFloat keyboardHeight = UIInterfaceOrientationIsPortrait(self.interfaceOrientation)?keyboardRect.size.height:keyboardRect.size.width;
CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
CGFloat animationStyle = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] floatValue];
self.tableViewOffset = self.tableView.contentOffset
UIEdgeInsets contentInsets = self.tableView.contentInset;
contentInsets.bottom = keyboardHeight;
[UIView animateWithDuration:duration delay:0 options:animationStyle animations:^{
self.tableView.contentInset = contentInsets;
} completion:nil];
}
- (void)keyboardWillHide:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
CGFloat animationStyle = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] floatValue];
UIEdgeInsets contentInsets = self.tableView.contentInset;
contentInsets.bottom = 0;
[UIView animateWithDuration:duration delay:0 options:animationStyle animations:^{
self.tableView.contentInset = contentInsets;
self.tableView.contentOffset = self.tableViewOffset;
} completion:nil];
}
关于ios - 出现键盘后UIWebView自动上移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25365005/