繁体   English   中英

如何在所有设备中每行快速布局三个图像

[英]How to layout three images per row in all devices swift

所以基本上我有一个如下的集合视图布局:

在此处输入图片说明

这是每行3张图片,与instagram彼此非常接近。 这里的问题是,当我使用ipad或iphone等较小的手机时,布局会失真。 这就是在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)
}

像这样重写UICollectionView:

class UICollectionViewCustom: UICollectionView {

    public override var bounds: CGRect {
        didSet {
            collectionViewLayout.invalidateLayout()
        }
    }
}

每当collectionView调整大小时,这都会更新collectionView布局。

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()
            }
        }
    }
}

结果是:

苹果手机 平板电脑

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM