我有一个 UIWebView 呈现一个包含输入字段 () 的页面。
当用户触摸字段输入数据时,UIWebView 向上和向左滚动以使该字段对用户保持可见。好吧。
我不介意它向上滚动(因为我表单下面的所有内容都被键盘隐藏了),但我想防止视图向左滚动。
有没有办法(html页面中的标题或iOS代码)来防止这种行为?
谢谢
我不知道如何完全防止滚动,但如果你不介意一点抖动,你可以将此处理程序添加到输入字段:
onfocus="setTimeout('window.scroll(0,0)',100)"
不漂亮但有效:
如果你根本不希望你的webView滚动,你可以实现UIWebView的UIScrollViewDelegate并在scrollViewDidScroll上将contentOffset设置为0
aWebView.scrollView.delegate = self
func scrollViewDidScroll(scrollView: UIScrollView) {
scrollView.contentOffset = CGPointMake(0, 0)
}
首先,您必须使用
UIKeyboardWillShowNotification
捕获键盘的显示。
然后将 UIScrollView(UIWebview 的)的 contentSize 宽度限制为屏幕宽度,这将确保屏幕不会水平滚动。
感谢@约书亚·史密斯
我做了同样的事情,但在运行时插入样式
@objc func keyboardWillShow(notification: Notification) {
if let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardFrame.height
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
let script = "window.scrollBy(0, \(keyboardHeight));"
// Execute JavaScript to scroll the web view when the keyboard appears
webView.evaluateJavaScript(script) { (result, error) in
if let error = error {
print("Error scrolling web view: \(error)")
}
}
}
}
@objc func keyboardWillHide(notification: Notification) {
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
// Reset the content offset of the web view when the keyboard hides
let script = "window.scrollTo(0, 0);"
// Execute JavaScript to scroll the web view to the top when the keyboard hides
webView.evaluateJavaScript(script) { (result, error) in
if let error = error {
print("Error scrolling web view: \(error)")
}
}
}
注意:确保您的 webView 启用了 javascript
webConfiguration.preferences.javaScriptEnabled = true
webConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = true