ios - 如何使 UICollectionViewCell 的动态宽度

标签 ios objective-c 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)
    }

最佳答案

这是最简单的解决方案。

您的 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)

}

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

关于ios - 如何使 UICollectionViewCell 的动态宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39223869/

相关文章:

ios - UICollectionView 滚动单列

ios - Collection View 单元格大小取决于 UITextView

ios - 使 UIView 和 UICollectionView 一起滚动

ios - 为什么 CoreBluetooth 一次又一次地发现相同的外围设备?

ios - 数组中的 UILabels 未显示在 ViewController 上

ios - 用另一个数组排序数组

objective-c - 基于文档的应用程序的核心数据版本控制

iphone - Storyboard Controller 未释放

iphone - 没有 xCode 的 Phonegap WEB-APP

iOS 将 MKMapView 转换为 UIImage。从不进入街区