如何正确调整UICollectionView的大小,使其完全显示其内容?我try 了很多方法,包括设置框架、调用reloadData和使布局无效:

self.collectionView.contentSize = CGSizeMake(300, 2000);
self.collectionView.frame = CGRectMake(0, 0, 300, 2000);
[self.collectionView reloadData];
[self.collectionView.collectionViewLayout invalidateLayout];

但这些都没有任何效果.按下按钮后,我仍能看到初始视图,如下所示:

集合视图仅在调整框架大小后显示部分内容

我有一个小的演示程序,其中有一个生成100个元素的数据源.在Interface Builder中,我最初将UICollectionView的大小设置为一个较小的值,以便不是所有元素都适合,然后按下一个按钮,然后执行上面的代码.我希望UICollectionView现在能显示所有元素,但事实并非如此.

EDIT: The demo program can be found at https://github.com/mjdemilliano/TestUICollectionView.

EDIT2: I have observed that the frame update is lost at some point, because if I press the button again, the current frame is back to the old value. After adding some log statements in the button event handler, the log output is:

before: frame = {{0, 58}, {320, 331}}, contentSize = {320, 1190}
update button pressed
after: frame = {{0, 0}, {300, 2000}}, contentSize = {300, 2000}
before: frame = {{0, 58}, {320, 331}}, contentSize = {320, 1190}
update button pressed
after: frame = {{0, 0}, {300, 2000}}, contentSize = {300, 2000}

I don't understand why the frame change is not kept, what is changing it.

在某个时刻,我将用从流布局中获得的值替换硬编码的值,但我想排除这种可能性,并尽可能简单地保留我的示例.

上下文:我最终想做的是:我有一个带有标签和图像等各种控件的可滚动视图,以及一个带有动态内容的集合视图.我想滚动所有这些内容,而不仅仅是collection视图,因此我没有使用collection视图自己的滚动功能,这些功能工作得很好.

推荐答案

我最终解决了这个问题,解决了所有的自动布局问题,使用约束来固定集合视图的高度.然后,每当我知道内容已更改时,我都会使用值collectionView.contentSize.height更新约束的值:

self.verticalLayoutConstraint.constant = self.collectionView.contentSize.height;

然后正确调整集合视图的大小,它在整个scrollview中表现良好.我已经用我的更改更新了GitHub测试项目.

To me, doing this by updating the constraint manually instead of being able to tell iOS: "make the frame height of the collection view as large as needed" does not feel right to me, but it's the best I have come up with so far. Please post a better answer if you have one.

Objective-c相关问答推荐

在哪里可以找到 iPad 示例代码

当 UITextField 成为第一响应者时如何使 UIScrollView 自动滚动

如何获取 NSDictionary 中的第一个元素?

使用自动布局自定义纵横比

XCTAssertEqual 错误:(3)不等于(3)

在 Interface Builder 中设计 UITableView 的section header

如何使用 NSString drawInRect 使文本居中?

Objective-C 浮点舍入

声明变量id和NSObject *有什么区别?

判断对象是 NSArray 还是 NSDictionary

从我在 iPhone 上的应用程序调用官方 *Settings* 应用程序

如何测试推送通知在我的应用程序中是否有效

UIWebView 不会zoom 内容以适应

未找到 Apple Mach-O 链接器警告目录

distanceFromLocation - 计算两点之间的距离

获取字符串的最后 2 个字符?

如何在 NSSet 或 NSArray 中搜索具有特定属性的特定值的对象?

如何修复UIPopoverController 已弃用警告?

如何本地化 iOS 故事板

带有Go按钮而不是返回的 iOS 键盘