我有一个UIScrollView包含几个动态调整大小的子视图。我可以调整和布局的子视图很好,但是当我设置滚动视图本身的内容大小时,底部的子视图被裁剪。滚动视图的内容大小高度应该大于它包含的视图高度之和的原因有什么原因吗?UIScrollView内容大小剪切子视图,当它不应该
这是我的情况更详细: 我有一个超级查看包含UIScrollView包含几个子视图。在superview的layoutSubviews方法中,我计算了每个子视图所需的大小,然后设置框架使子视图在屏幕之间垂直平铺,并在它们之间留出一点空间。完成后,我将UIScrollView的内容大小的高度设置为最后一个子视图的结尾(origin.y + size.height)。理论上,这意味着滚动视图的内容区域的底部应该与最后一个子视图的底部完全对齐。
但它没有。相反,最后一个子视图的一个很好的块被剪切。它仍然存在 - 如果向下滚动,我可以看到“反弹”期间的剩余部分。在横向模式下问题更加严重 - 底部子视图的很大一部分根本不可见。
子视图全部安排妥当。问题是UIScrollView的contentSize似乎需要比子视图的高度之和(加上它们之间的空间)大得多。这对我来说没有任何意义。此外,大小是“关闭”的数量是不同的 - 我重复使用这个视图多次不同的子视图,并且他们都是不同的数量。因此,简单地向内容视图高度添加常量将无济于事。
是什么导致内容大小(或我的身高计算)无法正常工作?
代码:
- (void)layoutSubviews
{
[super layoutSubviews];
CGFloat width = self.bounds.size.width - [self subviewLeftMargin] - [self subviewRightMargin]; // All subviews have same width as parent view
CGFloat x = [self subviewLeftMargin]; // All subviews should start at the far left of the view
CGFloat y = [self spaceBetweenSubviews]; // Running tally of the y coordinate for the next view
/* Adjust the subviews */
for(UIView *view in self.theVariousSubviews) {
/* Resize the view with the desired width, then let it size its height as needed */
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, width, view.frame.size.height);
CGSize newSize = [view sizeThatFits:view.frame.size];
/* Set the origin */
//The subviews are positioned correctly, so this doesn't seem to be a problem
view.frame = CGRectMake(x, y, newSize.width, newSize.height);
/* Have the view refresh its own layout */
[view setNeedsLayout];
/* Update the y value for the next subview */
y += newSize.height + [self spaceBetweenSubviews];
}
/* Resize the scroll view to ensure it fits all of the content */
CGFloat scrollViewHeight = y;
self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, scrollViewHeight);
//Content size is set to the same total height of all subviews and spacing, yet it is too small. Why?
}