Im trying to create a simple UICollectionView
in Swift with a custom UICollectionViewCell
. I have the following method in my UICollectionViewController
to set the size of a cell;
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (collectionView.frame.width / 3) - 10
let height = CGFloat(170)
return CGSize(width: width, height: height)
}
I then set constraints for the cell as follows;
private func setImageViewConstraints() {
itemImageView.translatesAutoresizingMaskIntoConstraints = false // enables Auto-Layout
itemImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true // center horizontally
itemImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true // 8pt from top of cell
// 1:1 Aspect Ratio
itemImageView.widthAnchor.constraint(equalToConstant: (self.frame.width - 4)).isActive = true
itemImageView.heightAnchor.constraint(equalTo: itemImageView.widthAnchor).isActive = true
}
private func setupLabelConstraints() {
itemLabel.translatesAutoresizingMaskIntoConstraints = false
itemLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
itemLabel.leftAnchor.constraint(equalTo: itemImageView.leftAnchor, constant: 0).isActive = true
itemLabel.rightAnchor.constraint(equalTo: itemImageView.rightAnchor, constant: 0).isActive = true
itemLabel.topAnchor.constraint(equalTo: itemImageView.bottomAnchor, constant: 4).isActive = true
itemLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -4).isActive = true
}
However, the height of the cell varies, depending on the height of it's content, for example;
How can I set the height of the cells so they are all the same? Thanks!