Drwalcorowiec Drwalcorowiec - 11 months ago 39
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
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() {
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
and after
I tried to put it in
but it didn't seem to work - mainly because the
didn't work. The only working so-so solution was putting
. 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 Source

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

 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

Simple as that! I hope that will help someone.