【问题标题】:UICollectionView cell layout not correctUICollectionView 单元格布局不正确
【发布时间】:2014-05-27 08:25:10
【问题描述】:

我对@9​​87654322@ 很陌生。我正在制作universal app。我想要的是在 iPad 上每行有 2 个单元格。但在 iPhone 上,每一行只有一个单元格。我能够正确设置 iPad 版本。但我无法理解 iPhone 的设置。

这是目前的设置。你可以在我的storyboard 上看到它看起来还不错。但是当我运行它时,我看到每行仍然有两个单元格。

有人可以帮我解决这个问题吗?

亲切的问候

【问题讨论】:

    标签: ios iphone objective-c uicollectionview uicollectionviewcell


    【解决方案1】:
        - (void)viewDidLoad
        {
            [super viewDidLoad];
    
            [self.collectionView registerClass:[CVCell class] forCellWithReuseIdentifier:@"cvCell"];
    
            // Configure layout
            UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
            [flowLayout setItemSize:CGSizeMake(100, 100)];
            [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
            [self.collectionView setCollectionViewLayout:flowLayout];
    
    
        }
        -(void)viewWillAppear:(BOOL)animated {
    
            [super viewWillAppear:animated];
            deviceModel = (NSString*)[UIDevice currentDevice].model;
            NSLog(@"device is = %@",deviceModel);
        }
        -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
            if ([deviceModel isEqualToString:@"iPhone Simulator"]) {
                return 1;
            }else
            {
                return 2;
            }
        }
        -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
              return 3;
    
        }
        -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
            // Setup cell identifier
            static NSString *cellIdentifier = @"cvCell";
    
            /* Uncomment this block to use subclass-based cells */
            CVCell *cell = (CVCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    
            if (indexPath.section == 0) {
                cell.backgroundColor = [UIColor redColor];
            }
            if (indexPath.section == 1) {
                cell.backgroundColor = [UIColor blueColor];
            }
            cell.titleLabel.text = [NSString stringWithFormat:@"item %ld",(long)indexPath.section];
            // Return the cell
            return cell;
    
        }
    

    检查此代码,它将在 iPhone 单元中为您提供一项,在 iPad 中为您提供两项..

    【讨论】:

    • 这是正确的方法吗?你是说每个部分应该只包含 1 个单元格?但这不是 UICollectionviews 的工作方式?
    • 无论您想要在单行中添加多少个下载组件,都将其添加为部分,然后它将按要求工作。