使用情节提要在 CollectionView 中仅显示两列和多行

2024-03-15

I want to display only two cells in a row, no matter what the iPhone screen size is. Like, End result required

我的故事板包含一个UICollectionView,通过约束连接。

The storyboard settings for the UICollectionView is, enter image description here

现在,当我在 6、5 秒或更短的时间内运行此命令时,一行中只会出现一个单元格。我使用的代码是,

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [categoryImages count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    homePageCells *cell = (homePageCells *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cells" forIndexPath:indexPath];
    cell.categoryName.text = [categoryNames objectAtIndex:indexPath.row];

    return cell;
}

我尝试使用代码检测屏幕尺寸并以编程方式分配适当的单元格尺寸,

- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize sizes;


    CGSize result = [[UIScreen mainScreen] bounds].size;
    NSLog(@"%f",result.height);
    if(result.height == 480)
    {
        //Load 3.5 inch xib
        sizes =CGSizeMake(170.f, 170.f);
        NSLog(@"3gs");
    }
    else if(result.height == 568)
    {
        //Load 4 inch xib
        sizes =CGSizeMake(130.f, 130.f);
        NSLog(@"5s");

    }
    else if(result.height == 667.000000)
    {
        //Load 4.7 inch xib
        sizes =CGSizeMake(160.f, 160.f);
        NSLog(@"6");

    }
    else
    {
        NSLog(@"else");

        sizes =CGSizeMake(170.f, 165.f);

    }
    return sizes;
}

但我也知道这不是正确的方法,所以请给我一个正确的方法来处理这个问题。


您不需要检查设备大小,因为我们可以使用collectionViewwidth 来计算单元格的宽度。使用单元格宽度,您可以根据需要计算高度。

还有一件事:你需要使用UICollectionViewDelegateFlowLayout&确认下面的委托&实现方法

  func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

   let padding: CGFloat =  50
   let collectionViewSize = collectionView.frame.size.width - padding

   return CGSizeMake(collectionViewSize/2, collectionViewSize/2)
   
}

更新:斯威夫特4.0

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let padding: CGFloat =  50
        let collectionViewSize = collectionView.frame.size.width - padding
        
        return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
    }

Note:我已经回答了这个问题,考虑到单元格是正方形的

附加信息:请确保您的预估尺寸为空https://i.stack.imgur.com/B9kmU.png https://i.stack.imgur.com/B9kmU.png

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用情节提要在 CollectionView 中仅显示两列和多行 的相关文章

随机推荐