iPad游乐场有不同的View.Frame

时间:2019-03-19 03:52:28

标签: swift xcode ipad swift-playground ipad-playgrounds

我正在尝试使用以下代码在iPad Playgrounds中显示此简单的ViewController:

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()

您可以看到,即使View1的框架显示为view.frame.width / 2,该视图仍然如下所示:

enter image description here

怎么了?谢谢。

2 个答案:

答案 0 :(得分:1)

Here’s how to get it to work

这是我使用过的解决方案,可以使它起作用。在Swift Playgrounds中,布局是通过viewDidLayoutSubview方法创建的,因此应在此处创建所有框架。

答案 1 :(得分:0)

您可以在初始化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