在单元格之间以及边距和单元格之间创建相等的空间UICollectionView

时间:2018-10-20 20:07:26

标签: ios swift uicollectionview

我有一个UICollectionView。在某些设备上,单元格拥抱设备的边缘,同时在中心留有很大的空隙。我尝试更改插图和最小间距,但两者均无效。我是在情节提要中创建的,因此没有与格式相关的代码。如何使像元之间的距离等于外部像元和边缘之间的距离,以使中间没有很大的间隙?谢谢。

图像边缘是设备的确切边缘

1 个答案:

答案 0 :(得分:1)

假设您使用的是UICollectionViewFlowLayout,并且单元格的大小是固定的:

自定义单元格代码:(我添加了一些阴影和圆角,请忽略它)

import UIKit

class CollectionViewCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)


        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 2.0)
        layer.shadowRadius = 5.0
        layer.shadowOpacity = 1.0
        layer.masksToBounds = false
        layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: contentView.layer.cornerRadius).cgPath
        layer.backgroundColor = UIColor.clear.cgColor

        contentView.layer.masksToBounds = true
        layer.cornerRadius = 10
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

查看控制器代码:

import UIKit

private let reuseIdentifier = "Cell"

class CollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        /// Class registration
        collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        /// Expected cell size
        let cellSize = CGSize(width: 120, height: 110)

        /// Number of columns you need
        let numColumns: CGFloat = 2
        /// Interitem space calculation
        let interitemSpace = ( UIScreen.main.bounds.width - numColumns * cellSize.width ) / (numColumns + 1)

        /// Setting content insets for side margins
        collectionView.contentInset = UIEdgeInsets(top: 10, left: interitemSpace, bottom: 10, right: interitemSpace)

        /// Telling the layout which cell size it has
        (self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = cellSize
    }

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

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

这是结果:

enter image description here