Предполагается, что вы используете 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
}
}
Вот результат: