Reputation: 481
I have a UIWebView presenting a page containing input fields ().
When the user touches the field to enter data, the UIWebView is scrolled up and left to make the field stay visible for the user. Well ok.
I don't mind it is scrolled up (because everything below my form is hidden by the keyboard) but I would like to prevent the view from being scrolled left.
Is there a way ( headers in the html page, or iOS code) to prevent this behavior ?
Thanks
Upvotes: 6
Views: 7360
Reputation: 8856
Thanks to @Joshua Smith
I have done the same but with inserting style on runtime
@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)")
}
}
}
Note: make sure javascript is enabled for your webView
webConfiguration.preferences.javaScriptEnabled = true
webConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = true
Upvotes: 0
Reputation: 403
not beautiful but effective:
If you don't want your webView to scroll at all, you can implement the UIWebView's UIScrollViewDelegate and set the contentOffset to 0 on scrollViewDidScroll
aWebView.scrollView.delegate = self
func scrollViewDidScroll(scrollView: UIScrollView) {
scrollView.contentOffset = CGPointMake(0, 0)
}
Upvotes: 3
Reputation: 3809
I don't know how to prevent the scrolling entirely, but if you don't mind a little jitter, you can add this handler to the input field:
onfocus="setTimeout('window.scroll(0,0)',100)"
Upvotes: 3
Reputation: 1579
First you will have to capture the display of a Keyboard using UIKeyboardWillShowNotification
.
Then restrict the contentSize width of the UIScrollView (of the UIWebview) to screen width which will ensure that the screen doesnot scroll horizontally.
Upvotes: 0