UICollectionView显示两行,但我只想要一行

时间:2014-06-10 02:26:47

标签: ios objective-c uicollectionview

当我使用UICollectionView时遇到一个奇怪的错误,请看下面的图片:

第三个细胞似乎以某种方式显示在第二个细胞下,第三个细胞的位置变成空白。

enter image description here

当我向外滚动视图然后返回(或重新加载视图)时,它变为正确:

enter image description here

以下是我使用的代码:

#pragma mark - UICollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {

    return datas.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
 }

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:    (NSIndexPath *)indexPath {

    static NSString *cellId = @"floorCell";
    FloorCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:cellId     forIndexPath:indexPath];
    NSDictionary *dic = [datas objectAtIndex:indexPath.row];
    cell.goodImageView.imageURL = [NSURL URLWithString:[dic objectForKey:@"img"]];
    cell.goodLabel.text = [dic objectForKey:@"title"];
    return cell;

}

我使用的布局是UICollectionViewFlowLayout,布局的委托如下:

#pragma mark – UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize retval = CGSizeMake(172 / 2.0, [FloorCollectionViewCell getHeight]);
    return retval;
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

我想知道原因以及如何解决问题?谢谢!

初始化collectionView的代码:

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(50, 0, 278, bottomView.frame.size.height)  collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor clearColor];
    [collectionView registerClass:[FloorCollectionViewCell class] forCellWithReuseIdentifier:@"floorCell"];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [bottomView addSubview:collectionView];

ps:我认为我已经通过将collectionView的高度更改为单元格的高度而不是整个灰色超视图的高度来解决问题。但我还是不知道原因,灰色超级视图的高度不足以容纳两个单元格!

更改的代码:

collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(50, 0, 278, [FloorCollectionViewCell getHeight])  collectionViewLayout:layout];

1 个答案:

答案 0 :(得分:1)

我不知道是否还有一点要回答这个问题,但为了将来你可以通过在集合视图本身上设置高度约束来解决这个问题这将强制集合视图不进入多行模式。这通常发生在您设置具有不同优先级的自动布局约束并且有足够的空间供集合视图扩展时。

相关问题