Reputation: 1479
Hey i asked similar question some Days ago but no on could help me and no i'm think im closer to the problem. I have an WebView on my rootViewController and saved some Values for zoom scale and position of an local PDF, now i want set the Webview to this values when it appears so i tried the following.
override func viewDidAppear(animated: Bool) {
doLayoutThings()
}
func doLayoutThings(){
if(defaults.objectForKey("positionY") != nil){
WebView.scrollView.setZoomScale(defaults.objectForKey("zoomlevel") as! CGFloat, animated: false)
let offest = CGPoint(x: defaults.objectForKey("positionX") as! CGFloat, y: defaults.objectForKey("positionY") as! CGFloat)
WebView.scrollView.setContentOffset(offest, animated:false)
println(defaults.objectForKey("zoomlevel") as! CGFloat)
}
I know that there are the correct values are saved to UserDefaults but the Webview looks if i didn't make any scrolling or zooming. I'm really happy about any solution Ideas.
Upvotes: 0
Views: 4080
Reputation: 774
I am used this link to resolved this issue
In Swift
Initially i am try to change the web view zoom scale but it was not so working fine .
webview.scrollView.setZoomScale(1.5, animated: true)
so i try to change it in webViewDidFinishLoad
func webViewDidFinishLoad(_ webView: UIWebView) {
webview.scalesPageToFit = true
let str = "var meta = document.createElement('meta');"
let str1 = "meta.setAttribute( 'name', 'viewport' ); "
let str2 = "meta.setAttribute( 'content', 'width = device-width, initial-scale = 1.0, user-scalable = yes' ); "
let str3 = "document.getElementsByTagName('head')[0].appendChild(meta)"
webview.stringByEvaluatingJavaScript(from: "\(str)\(str1)\(str2)\(str3)")
}
if you need to change the zoom level, change the "initial-scale" to see the effect of initial level zooming. It's really helpful for me. Thanks "UIWebView set initial zoom scale programmatically when loading an external website?"
Upvotes: 1
Reputation: 27620
Setting the zoom scale in viewDidAppear
is fine but you cannot set the contentOffset
before the web view has loaded its content. So you have to set a delegate on the UIWebView
and then set the contentOffset in the delegate method:
override func viewDidLoad() {
webView.delegate = self
}
func webViewDidFinishLoad(webView: UIWebView) {
let offset = CGPoint(x: defaults.objectForKey("positionX") as! CGFloat, y: defaults.objectForKey("positionY") as! CGFloat)
webView.scrollView.setContentOffset(offset, animated: false)
}
Upvotes: 0