UIScrollView - 当子视图溢出滚动视图边界时如何将子视图换行?

UIScrollView - How to wrap subviews to new line when subview overflows scroll view bounds?

我正在创建一个滚动视图,它将具有相同高度和不同宽度的子视图。 我想知道当最后一个子视图超过滚动视图宽度界限时将子视图换行的最佳方法是什么?

我尝试检测子视图是否在滚动视图边界之外,然后增加 yOffset,但这似乎不起作用:

if !CGRectContainsPoint(self.scrollView.frame, CGPointMake(subView.frame.origin.x+subView.frame.size.width, subView.frame.origin.y))
 {
      scrollViewOffsetY += subView.frame.height
      scrollViewOffsetX = 5
      subView.frame.origin = CGPointMake(scrollViewOffsetX, scrollViewOffsetY)
 }

想通了。这是我所做的:

    var scrollViewOriginX: CGFloat = 0.0
    var scrollViewOriginY: CGFloat = 0.0

    for var index = 0; index < 10; index++
    {

            var subview = UIView()
            //...customize your subview here.../

            // Check if subview is out of scroll view's bounds
            if !CGRectContainsPoint(self.scrollView.bounds, CGPointMake(scrollViewOriginX + scrollViewOffsetX + subview.frame.size.width, 0))
            {
                // Increase Y Offset
                scrollViewOriginY += subview.frame.height + scrollViewOffsetY
                // Reset X Offset
                scrollViewOriginX = scrollViewOffsetX

                subview.frame.origin = CGPointMake(scrollViewOriginX, scrollViewOriginY + scrollViewOffsetY)
            }
            else
            {
                subview.frame.origin = CGPointMake(scrollViewOriginX + scrollViewOffsetX, scrollViewOriginY + scrollViewOffsetY)
            }

            self.scrollView.addSubview(subview)
            scrollViewOriginX += subview.frame.width + scrollViewOffsetX

            self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.width, scrollViewOriginY+subview.frame.height+scrollViewInsetBottom)
    }