如何将 UIView 的大小调整为特定的高度和宽度,包括其子视图?

How to resize a UIView to a specific height and width including its subviews?

我在尝试正确调整 UIView 的大小时遇到​​问题。

示例场景如下:

// other view controller initializations

let containerView = UIView(frame: CGRect(x:0, y:0, width: self.view.bounds.width, height: self.view.bounds.height))
self.view.addSubview(containerView)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

let subView = UIView(frame: CGRect(x:0, y:0, width:containerView.bounds.size.width / 2, height: containerView.bounds.size.height))
containerView.addSubview(subView)
subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

假设我想将 containerView 的大小调整为特定的高度和宽度,这样子视图也会与 containerView 平行调整自身大小。

我怎样才能做到这一点?

不要忘记为 subView

设置以下 属性
subView.autoresizesSubviews = true;

根据Apple documentation

An integer bit mask that determines how the receiver resizes itself when its superview’s bounds change.

所以使用你的例子它看起来像这样

let containerView = UIView(frame: CGRect(x:0, 
                                         y:0, 
                                         width: self.view.bounds.width, 
                                         height: self.view.bounds.height))

containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(containerView)

let subView = UIView(frame: CGRect(x:0, 
                                   y:0, 
                                   width: containerView.bounds.size.width / 2, 
                                   height: containerView.bounds.size.height))

subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
subView.autoresizesSubviews = true;
containerView.addSubview(subView)

我能够通过使用 UIStackView.

实现我想要的
let stackView = UIStackView(frame: .zero)
currentPage.addSubview(stackView)
constraintViewToSuperView(view: stackView) // my helper function to constraint stackview to bounds of parent

stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .fillProportionally
stackView.spacing = 1
stackView.backgroundColor = .red

关键是将 UIStackview 限制在 parent 的范围内。然后我对 parent 所做的任何调整也会按比例调整 UIStackview 的 children.