IPad Playground Has Different View.Frame

821 Views Asked by At

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.

2

There are 2 best solutions below

0
HeySaiK On BEST ANSWER

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.

3
jasnstu On

You can set your preferred size after you init your ViewController:

import UIKit
import PlaygroundSupport

class VC: 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)
    }
}

let vc = VC()
vc.preferredContentSize = CGSize(width: 768, height: 1024)

PlaygroundPage.current.liveView = vc

Playground with preferredContentSize

Playground without preferredContentSize