首页 > 解决方案 > 如何在所有设备中快速布局每行三个图像

问题描述

所以基本上我有一个看起来像这样的集合视图布局:

在此处输入图像描述

这是一个每行 3 个图像,像 instagram 一样彼此非常接近。这里的问题是,当我使用 ipad 或像 iphone se 这样的小型手机时,布局会失真。这是它在 ipad 上的样子

在此处输入图像描述

集合视图布局代码是这样的:

    func callCustomFlowLayout(collectionView: UICollectionView) {
    let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout

    let itemSpacing: CGFloat = 1
    let itemsInOneLine: CGFloat = 3
    flow.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
    let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1) //collectionView.frame.width is the same as  UIScreen.main.bounds.size.width here.
    flow.itemSize = CGSize(width: floor(width/itemsInOneLine), height: width/itemsInOneLine)
    flow.minimumInteritemSpacing = 1
    flow.minimumLineSpacing = 1
}

感谢您对未来的任何帮助。我只希望它是每行 3 个图像,并根据设备的大小调整图像大小。

这是我的布局代码

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

    let cellsAcross: CGFloat = 3
    let spaceBetweenCells: CGFloat = 1
    let dim = (collectionView.bounds.width - (cellsAcross - 1) * spaceBetweenCells) / cellsAcross

    return CGSize(width: dim, height: dim)
}

标签: iosswiftuicollectionviewios-autolayout

解决方案


class CollectionView: UICollectionView {

    private let numberOfCellsPerRow = 3
    private let spacing: CGFloat = 1

    private var flowLayout: UICollectionViewFlowLayout? {
        return collectionViewLayout as? UICollectionViewFlowLayout
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        sharedInit()
        updateItemSize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
        updateItemSize()
    }

    private func sharedInit() {
        flowLayout?.minimumInteritemSpacing = spacing
        flowLayout?.minimumLineSpacing = spacing
    }


    private func updateItemSize() {
        let cellWidth = floor((bounds.width - (CGFloat(numberOfCellsPerRow) - 1) * spacing) / CGFloat(numberOfCellsPerRow))
        flowLayout?.itemSize = CGSize(width: cellWidth, height: cellWidth)
        flowLayout?.invalidateLayout()
    }

    override var bounds: CGRect {
        didSet {
            if bounds != oldValue {
                updateItemSize()
            }
        }
    }
}

结果是:

苹果手机 平板电脑


推荐阅读