如何正确对齐这些collectionview单元格?

时间:2018-09-06 18:45:29

标签: ios swift uicollectionview uikit uicollectionviewcell

我正在创建一个使用集合视图的页面。布局类似于Apple的Music应用,其中每行显示两个方形单元格

I want a layout like this-this layout has super equal margins around but in my app the first collection cell is stuck to the left edge and the 2nd cell is stuck to the right edge

    private let cellReuseIdentifier = "cellReuseIdentifier"

    class FeedViewController: UICollectionViewController {

        override func viewDidLoad() {
            super.viewDidLoad()
            collectionView?.backgroundColor = .white
            setupNavBar()
            setupCollectionView()
        }

        func setupCollectionView() {
            collectionView?.register(FeedCollectionViewCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)
        }

        override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 6
        }

        override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath)
            return cell
        }

    }

    extension FeedViewController: UICollectionViewDelegateFlowLayout {

        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            let padding: CGFloat =  25
            let collectionViewSize = collectionView.frame.size.width - padding

            return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)

        }

    }

2 个答案:

答案 0 :(得分:0)

在集合视图设置功能中,您可以使用布局属性来设置集合视图插图和单元格之间所需的空间:

guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }

layout.sectionInset = UIEdgeInsets(top: yourTopValue, left: yourLeftValue, bottom: yourBottomValue, right: yourRightValue)
layout.minimumInteritemSpacing = yourSpacing
layout.minimumLineSpacing = yourSpacing

答案 1 :(得分:0)

使用以下代码来满足您的需求。

填充值应为所有三个空格(左,中,右)的和 假设padding值= 25,那么在布局计算中应该考虑75,以获得确切的间距。

然后将左,上,中和右空间设置为25(您想在此处添加空间)。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let cellWidth: CGFloat = (collectionView.frame.size.width / 2) - ((padding value * 3)/2)
    let cellHeight: CGFloat = (collectionView.frame.size.height / 2)  - ((padding value * 3)/2) 
    return CGSize.init(width: cellWidth, height: cellHeight) 
}

确定可以使用