How to stop the size of frame becomes 1024x768 in Swift playground

Viewed 99

The frame of the main view in UIViewController becomes 1024x768.

At first, the problem is not obvious, but later when doing layout, it becomes troublesome. How can I make sure the frame stays the same size as what I set with .preferredContentSize ?

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    override open func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.view.frame //When run playground shows 1024x768
    }
}
let viewController = MyViewController()
viewController.preferredContentSize = CGSize(width: 375, height: 667) // set to different size


PlaygroundPage.current.liveView = viewController
1 Answers

Auto-layout has not finished in viewDidAppear().

You can get the frame size in viewWillAppear and viewDidLayoutSubviews, both of which are called more than once - but the last call will have the correct frame size.

You can also get it in viewDidAppear but that may be too late for your needs.

A common approach is to create a var holding the initial size, and then run any code which needs the actual frame size in viewDidLayoutSubviews if the current frame size is different from the saved size (and the updating the saved size).

Related