childViewController.view.frame 在 UIView 中呈现不同的值

childViewController.view.frame in UIView present different value

我在项目中使用 childViewController 来分隔视图,但出现了一些奇怪的问题,这是我的代码。

class ViewController: UIViewController {

    var container = UIView()
    var childVC = ChildViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        addChildViewController(childVC)
        childVC.didMove(toParentViewController: self)

        addChildView()

        setContainerFrame()
    }

    func setContainerFrame() {
        container.frame = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 100)
        container.backgroundColor = .red
        view.addSubview(container)
    }

    func addChildView() {
        let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        childVC.view.frame = frame
        childVC.view.backgroundColor = .green
        container.addSubview(childVC.view)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("childVC.view.frame: \(childVC.view.frame)")
    }
}


class ChildViewController: UIViewController {
}

当我在 ViewController 的 viewDidLoad() 中交换调用 func addChildView() 和 func setContainerFrame() 的顺序时,xcode'控制台打印不同的帧日志。

出现奇怪的行为是因为在 addChildView() 函数中,您将子视图控制器的视图作为子视图添加到容器视图,但容器视图的框架在尚未调用的函数 setContainerFrame() 中设置。这意味着您正在向尚未设置框架的视图添加子视图。

这是由于 childVC.view 的 autoresizingMask。默认情况下,这被设置为具有灵活的宽度和高度。因此,如果您设置容器的框架,然后设置 childVC.view 的框架,那么您将获得您设置的实际值,但如果您反转它并设置 childVC.view 的框架,然后设置容器的框架的 childVC.view 自动更新为具有相同的相对宽度和高度。

例如,如果容器的框架尺寸为 100 x 100,然后您将其更改为 200 x 200,则 childVC.view 的框架尺寸将加倍。

要删除此设置 childVC.view.autoresizingMask = [],使其保持您的设置。