【问题标题】:How do I apply aspect ratio constraints to a custom UICollectionViewCell programmatically?如何以编程方式将纵横比约束应用于自定义 UICollectionViewCell?
【发布时间】:2015-05-08 19:23:47
【问题描述】:

我正在尝试创建一个显示相册封面的网格样式视图。我想要每行 3 张专辑封面。棘手的部分是让单元格根据使用的设备适当增加大小,例如iPhone 4s/5/5s/5c/6/6 plus,无论使用什么设备,每行始终显示 3 个项目/单元格。

我从来没有能够做到这一点。我正在考虑像这样手动设置尺寸:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if DeviceHelper.DeviceType.IS_IPHONE_4_OR_LESS {
        return CGSizeMake(115, 140)
    } else if DeviceHelper.DeviceType.IS_IPHONE_5 {
        return //size
    } else if DeviceHelper.DeviceType.IS_IPHONE_6 {
        return //size
    } else {
        return //size 
    }
}

我有一个帮助器来确定正在使用的设备,我可以从应用程序中的任何位置调用它。但是有没有办法确保无论使用什么设备,每行都始终显示 3 个单元格,并且还显示相同的填充,如下所示:

纵横比限制很有帮助,但这次我无法将它们应用到单元格,因为界面生成器不允许这样做。有没有直接的方法可以做到这一点?

提前感谢您的宝贵时间。

【问题讨论】:

    标签: ios swift cocoa-touch uicollectionview uicollectionviewcell


    【解决方案1】:

    删除默认单元格间距:

    试试这个代码:

    只需设置 numberOfCellInRow 的值即可获得集合视图中一行单元格的数量

    Obj-C

    -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
       int numberOfCellInRow = 3;
       CGFloat padding = 5.0;
       CGFloat collectionCellWidth =  [[UIScreen mainScreen] bounds].size.width/numberOfCellInRow;
       CGFloat finalWidthWithPadding = collectionCellWidth - padding;
       return CGSizeMake(finalWidthWithPadding , finalWidthWithPadding);
    }
    

    斯威夫特

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        var numberOfCellInRow : Int = 3
        var padding : Int = 5
        var collectionCellWidth : CGFloat = (self.view.frame.size.width/CGFloat(numberOfCellInRow)) - CGFloat(padding)
        return CGSize(width: collectionCellWidth , height: collectionCellWidth)
    }
    

    我认为它适用于所有设备。

    【讨论】:

    • 只是想把它转换成 swift。
    • 这对我不起作用。每行有 2 个项目,中间有很大的间隙。
    • 现在可以使用了,谢谢。你能修改代码以包含填充吗?
    • 缺少垂直填充,并且您假设集合视图单元格是正方形。 OP不是在问保持单元格的纵横比吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 2020-01-16
    • 2015-05-25
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多