如何在 Swift playground 中停止 frame 的大小变为 1024x768

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

UIViewController中主视图的frame变为1024x768

一开始问题不明显,后来做布局的时候就麻烦了。 如何确保框架与我使用 .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

自动布局尚未在 viewDidAppear() 内完成。

您可以在 viewWillAppearviewDidLayoutSubviews 中获取帧大小,这两个调用都不止一次 - 但最后一次调用 正确的帧大小。

您也可以在 viewDidAppear 中获取它,但可能为时已晚,无法满足您的需求。

一种常见的方法是创建一个 var 保存初始大小,然后 运行 任何需要实际帧大小的代码 viewDidLayoutSubviews if 当前帧大小与保存的大小不同(以及更新保存的大小)。