如何制作 UICollectionViewCell 的动态宽度

san*_*hra 5 objective-c ios uicollectionview

我想UICollectionViewCell动态设置宽度。我在 swift 中找到了一些代码,我想要 Objective-C 中的代码。

let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
    if indexPath.item % 3 == 0 {
        let cellWidth = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right))
        return CGSize(width: cellWidth, height: cellWidth / 2)
    } else {
        let cellWidth = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right) - flowLayout.minimumInteritemSpacing) / 2
        return CGSize(width: cellWidth, height: cellWidth)
    }
Run Code Online (Sandbox Code Playgroud)

Sun*_*Kim 5

这是最简单的解决方案。

你的 UIViewController 应该实现 UICollectionViewDelegateFlowLayout。那么下面的函数需要在你的 UIviewController 上实现。

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = self.collectionView.frame.size.width / 2;


    return CGSize(width: width, height: 230)

}
Run Code Online (Sandbox Code Playgroud)

此外,您可以在故事板上调整每个单元格的间距值。单击 collectionView 然后查看大小检查器。


Sai*_*dra 4

你可以试试这个...

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

    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*) collectionView.collectionViewLayout;

    if (indexPath.item % 3 == 0) {
        float cellWidth = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right));
        return CGSizeMake(cellWidth, cellWidth / 2);
    } else {
        float cellWidth = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right) - flowLayout.minimumInteritemSpacing) / 2;
        return CGSizeMake(cellWidth, cellWidth);
    }
}
Run Code Online (Sandbox Code Playgroud)