UICollectionView中的单元格重叠

时间:2014-02-25 15:27:33

标签: ios iphone uicollectionview

我正在使用ViewController,我以这种方式添加UICollectionView:

UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[collectionViewFlowLayout setMinimumInteritemSpacing:2];
[collectionViewFlowLayout setMinimumLineSpacing:4];
[collectionViewFlowLayout setHeaderReferenceSize:CGSizeMake(320, 30)];

CGRect collectionViewFrame = self.view.bounds;
self.collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:collectionViewFlowLayout];
self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

self.collectionView.delegate = self;
self.collectionView.dataSource = self;

[self.collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:myCellIdentifier];

[self.view addSubview:self.collectionView];

这就是我初始化自定义单元格对象的方式(我确保每个单元格的框架填满整个屏幕宽度,以便在UICollectionView中垂直渲染单元格):

CGSize mySize = CGSizeMake(320, 158);
self.myTitle = [[UILabel alloc ] initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];
[self.myTitle setTextColor:[UIColor whiteColor]];
[self.myTitle setBackgroundColor:[UIColor greenColor]];
[self.myTitle setTextAlignment:NSTextAlignmentLeft];
[self.myTitle setNumberOfLines:1];
[self.myTitle setText:@"My Title"];
[self addSubview:self.myTitle];

这是我在initWithNibName中初始化单元格框架的方式:

CGSize mySize = CGSizeMake(320, 158);
self = [super initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];

这是我的cellForItemAtIndexPath代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:myCellIdentifier forIndexPath:indexPath];

    return cell;
}

现在我有四个这样的细胞,但它们是重叠的。我究竟做错了什么?谢谢!

2 个答案:

答案 0 :(得分:4)

实施UICollectionViewFlowLayout委托调用:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(320, 158);
}

或者由于所有尺寸都是常量,只需在Flow布局中指定尺寸,如下所示:

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.itemSize = CGSizeMake(320, 158);

答案 1 :(得分:0)

numberOfSectionsInCollectionView:方法中使用

  

[self.collectionView.collectionViewLayout invalidateLayout];

我希望它会奏效!