Search code examples
swiftcgrect

How to create a rect from a size?


Ultimately, I'm trying to retrieve the contentSize of my dynamic UIScrollView.

I'm doing this with this loop :

    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

The body of the loop is syntactically incorrect though. This is because you can't make a CGRectMake with the variable size.

Would anyone know how I can properly create this shape? Is there a better way to refactor this code to make it more elegant?


Solution

  • You need to add x and y coordinates for it to work. Should be something like this:

    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