1

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.

pesch
  • 1,976
  • 2
  • 17
  • 29
  • If you drag the edge of the preview half of the screen all the way to the left—so that you get a full screen preview—does the red view still cover the full width? I suspect that the problem is that the `MyViewController` live view is too large to fit the preview and thus appear to crop to the preview size. – David Rönnqvist Mar 19 '19 at 05:01
  • It's kind of weird, if I drag it out all of the way, if I drag it out all the way, it covers around 60% of the width. –  Mar 19 '19 at 05:10

2 Answers2

1

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.

HeySaiK
  • 480
  • 1
  • 6
  • 17
0

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

jasnstu
  • 1
  • 1
  • 2
  • Didn’t work for me. Keep in mind that I’m running on an iPad. Thank you for the help! –  Mar 19 '19 at 04:30
  • @NikolasIoannou, that's frustrating. I just pulled out my iPad version and it looks like the preview on the right isn't doing the correct thing (I wonder if there's a way to make the liveView fullscreen). If you tap the little square under your `addSubview(_:)` call, it looks like it _should_ be working correctly https://i.stack.imgur.com/h8k3C.png – jasnstu Mar 19 '19 at 04:49
  • Yes, that is odd. I'll have to look into that. –  Mar 19 '19 at 05:11