UICollectionView框架更改时调整UICollectionViewFlowLayout

时间:2013-08-23 21:54:42

标签: objective-c uicollectionview

我有一个以编程方式创建的UICollectionView及其UICollectionViewFlowLayout。这个代码如下:

- (UICollectionView *)createCollectionToDisplayContent:(NSArray *)array ViewWithCellIdentifier:(NSString *)cellIdentifier ofWidth:(CGFloat)width withHeight:(CGFloat)height forEmailView:(EmailView *)emailView
 {

 CGFloat minInterItemSpacing;

 if (!self.orientationIsLandscape) minInterItemSpacing = 9.0f;
    else minInterItemSpacing = 20.0f;

 UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
     layout.itemSize = CGSizeMake(220.0f, 45.0f);
     layout.sectionInset = UIEdgeInsetsMake(5.0f, 0.0f, 5.0f, 0.0f);
     layout.minimumLineSpacing = 10.0f;
     layout.minimumInteritemSpacing = minInterItemSpacing;

    //get pointer to layout so I can change it later 
    emailView.personLabelsLayout = layout;

 UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(40, 4, width, height) collectionViewLayout:layout];
     collectionView.dataSource = emailView;
     collectionView.delegate = emailView;
     collectionView.scrollEnabled = NO;
     collectionView.userInteractionEnabled = YES;
     collectionView.backgroundColor = [UIColor clearColor];
     [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
     collectionView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin);
     [collectionView reloadData];

 return collectionView;
 }

此代码可以很好地初始显示集合视图。我的问题是在旋转设备时尝试更改流布局。我使用struts和spring处理集合视图框架中的更改(参见上文),并且在willAnimateRotationToInterfaceOrientation方法中,我调整了流布局的minimumInterItemSpacing属性,最后在集合视图上调用reload数据。这是代码:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{       

CGFloat minInterItemSpacing;

if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
    minInterItemSpacing = 20.0f;
}  else {
       minInterItemSpacing = 9.0f;
   }

self.visibleEmailView = //...more code
self.visibleEmailView.personLabelsLayout.minimumInteritemSpacing = minInterItemSpacing;
[self.visibleEmailView.personLabelsCollectionView reloadData];    

//other stuff...  

}

最终,当旋转视图时,流布局应该会显着调整:就minimumInterItemSpacing而言,还要根据它显示的列数来调整。但是,布局没有按照我的预期进行调整。我无法弄清楚究竟发生了什么。看起来似乎minimalInterItemSpacing没有在旋转时重置,并且看起来对于每个单元格,同一个单元格被多次绘制。此外,我正在崩溃,说:

"the collection view's data source did not return a valid cell from -collectionView:cellForItemAtIndexPath: for index path <NSIndexPath 0x9be47e0> 2 indexes [0, 6]"

在尝试开始缩小这里发生的事情的时候,我想知道是否有人可以告诉我我的方法是否正确,和/或我的代码中是否存在可能导致部分或全部错误的明显错误这种时髦的行为。

1 个答案:

答案 0 :(得分:0)

你是否正在实施这样的事情?

- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
]