如何从尺寸创建矩形?

How to create a rect from a size?

最后,我尝试检索我的动态 UIScrollView 的 contentSize。

我正在用这个循环来做这个:

    var contentRect = CGRectZero
    for view: UIView in self.scrollView.subviews {
        var size : CGSize = (view.text?.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)]))
        contentRect = CGRectUnion( contentRect, CGRectMake(size) )
    }
    scrollView.contentSize = contentRect

虽然循环体在语法上不正确。这是因为您不能使用变量 size.

创建 CGRectMake

有谁知道我怎样才能正确地创建这个形状?有没有更好的方法重构这段代码,让它更优雅?

您需要添加 x 和 y 坐标才能正常工作。应该是这样的:

var contentRect = CGRectZero
for view: UIView in self.scrollView.subviews {
    var size : CGSize = (view.text?.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)]))
    let rect = CGRectMake(0, 0, size.width, size.height)
    contentRect = CGRectUnion( contentRect, rect )
}
scrollView.contentSize = contentRect