I have added a collection view
and added an image view
for each cell. I was able to add and scale the image views for each cell, but they were slightly off centre. I set the image view's centre to the cell's centre, but this caused only one image to now show.
Here is the code:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CarCell", for: indexPath)
let carImageView = UIImageView(image: UIImage(systemName: "car"))
carImageView.frame = cell.contentView.frame
carImageView.center = cell.center
carImageView.contentMode = .scaleAspectFit
cell.addSubview(carImageView)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let columns: CGFloat = 2
let collectionViewWidth = collectionView.bounds.width
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let spaceBetweenCells = flowLayout.minimumInteritemSpacing * (columns - 1)
let adjustedWidth = collectionViewWidth - spaceBetweenCells
let width: CGFloat = floor(adjustedWidth / columns)
let height: CGFloat = width
return CGSize(width: width, height: height)
}
Here is the outcome:
And the view hierarchy shows all cells are created with their UIViews
, but not the image views
:
Removing the line carImageView.center = cell.center
makes all images reappear again, but off-centre. Does anyone know how to fix this?