Drwalcorowiec Drwalcorowiec - 2 months ago 11
Swift Question

How to apply scalePagesToFit in another lifecycle moment in Swift?

I am making some simple view based on webView. I wanted to call

scalePagesToFit = true
simply in
viewDidLoad
but this didn't work properly. The views that I wanted to fit - were ok, but views that were already showed properly (with no need to resize), have been resized and stretched - and this is what I wanted to avoid. That's the reason I added checking if loaded content is wider than screen.

private var needsResize: Bool = false {
didSet {
if self.needsResize == true {
self.webView.scalesPageToFit = true
} else {
self.webView.scalesPageToFit = false
}}}

override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
self.webView.scrollView.maximumZoomScale = 20
self.webView.scrollView.minimumZoomScale = 0.5

(...)
}

func webViewDidFinishLoad(webView: UIWebView) {
let scrollWidth = self.webView.scrollView.contentSize.width
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidght = screenSize.width

if scrollWidth > screenWidght {
self.needsResize = true
}
}


The main problem is the lifecycle is not working in my favor here. I can measure the content just before
viewWillAppear
and after
viewDidLoad
.
I tried to put it in
viewWillAppear
or
viewDidAppear
but it didn't seem to work - mainly because the
scalesPagesToFit
didn't work. The only working so-so solution was putting
viewDidLoad
in
didSet
. But You can guess how it was working - the whole view was blinking and reloading for content wider than screen.
Do You have any ideas or hints for me?

Answer

I solved that by moving making new method called e.g. loadWebContent(). I move everything webview loading related here so it's like that

loadWebContent(){
 self.webView.loadHTMLString(text, baseURL: NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath))
}

Then it's called once in viewDidLoad than second time in didSet. And didSet has been rewritten and simplified.

  didSet {
     self.webView.scalesPageToFit = self.needsResize
     loadWebContent()
}

Simple as that! I hope that will help someone.