ios - 如何以编程方式更改 UICollectionView 的大小?

标签 ios objective-c uicollectionview

我在界面生成器中创建了一个 UICollectionView。我用

引用了它
@property (strong, nonatomic) IBOutlet UICollectionView *contactList;

在我的 .h 文件和@synthesize contactList 中;在我的 .m 文件中。
我尝试使用以下代码在纵向和横向中实现略有不同的布局:

- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation {
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
        UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout*)contactList.collectionViewLayout;
        flow.sectionInset = UIEdgeInsetsMake(48, 80, 48, 0);
        flow.minimumLineSpacing = 80;
    } else if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
        UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout*)contactList.collectionViewLayout;
        flow.sectionInset = UIEdgeInsetsMake(48, 64, 48, 0);
        flow.minimumLineSpacing = 64;
    }
}

这很好用,但我还想更改大小(横向时每页有 2*3 网格,纵向时是 3*2 网格)。我试过这样设置大小:

CGRect frame = [contactList frame];
frame.size.width = 960;
[contactList setFrame:frame];

但它不会更新。没有错误,只是 View 没有更新。它只是保持与以前相同的大小。我必须做什么才能更新 View ?

最佳答案

在我的应用程序中,我总是使用这个:

[self.contactList performUpdates:^{
  CGRect frame = [contactList frame];
  frame.size.width = 960;
  [contactList setFrame:frame];

  [self.contactList.collectionViewLayout invalidateLayout];
} completion:nil];

这应该设置您的框架并更新您的布局。

关于ios - 如何以编程方式更改 UICollectionView 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18358118/

相关文章:

ios - 保存图像数组的最佳方法?

objective-c - 使用 UISegmentedControl 通过 NSUserDefaults 保存 mapKit 首选项 - 无法正常工作

C++ 代码在以 Objective-c 为主的项目中运行速度非常慢

swift - Collection View 单元格垂直顶部对齐

ios - UICollectionView 保持水平列表滚动位置

ios - 1 个 UIviewcontroller 中的 2 个 UIcollectionview 具有 2 个不同的 UIcollectionflowlayout?

android - 单击文本字段时防止表单向上滚动

iphone - 核心图 iOS 反转 Y 轴

ios - 如何将持有 int 的 iOS id 类型转换为 NSString?

ios - 我如何计算包含特定艺术家的文件?