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

Kev*_*vin 5 objective-c ios uicollectionview

我在界面构建器中创建了一个UICollectionView.我引用了它

@property (strong, nonatomic) IBOutlet UICollectionView *contactList;
Run Code Online (Sandbox Code Playgroud)

在我的.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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这完美地工作,但我也想改变大小(在横向上我每页有2*3网格,而在肖像中它是3*2网格).我尝试设置这样的大小:

CGRect frame = [contactList frame];
frame.size.width = 960;
[contactList setFrame:frame];
Run Code Online (Sandbox Code Playgroud)

但它不会更新.没有错误,但视图没有更新.它只是保持与以前相同的大小.我需要做些什么来更新视图?

jbb*_*nni -1

你什么时候修改框架contactList?在 VC 初始化时,outlet 为零。ViewDidLoad连接插座后,您的视图控制器会收到呼叫。

我怀疑contactList当你的调整大小代码被执行时,它仍然为零。将该代码的执行转移到一个ViewDidLoad方法中,您将能够访问真正的交易。

您可以通过将以下内容添加到调整框架大小的位置来轻松测试该理论:

NSLog(@"contactList is: %@",contactList.description);
Run Code Online (Sandbox Code Playgroud)