swiftxcodeipadswift-playgroundipad-playgrounds

IPad Playground Has Different View.Frame


I am trying to show this simple ViewController in iPad Playgrounds with this code:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    setupViews()
}

func setupViews() {
    let view1 = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width/2, height: 100))
    view1.backgroundColor = .red
    view.addSubview(view1)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

You can see that, even though it says view.frame.width/2 for the frame of View1, the view still looks like this:

enter image description here

What is wrong? Thank you.


Solution

  • Here’s how to get it to work

    This is the solution I used which got it to work. In Swift Playgrounds, the layout is created in the viewDidLayoutSubview method so all frames should be created there.