Target: I have a UICollectionView with default 7 columns and 6 rows of cells. Now the user shall be able to change the amount of columns and rows via a UIStepper. Like so:
var numberOfColumns: Int = 7
@IBAction func changeNumberOfColumns(_ sender: UIStepper) {
numberOfColumns = Int(sender.value)
boardSizingCollectionView.reloadData()
}
extension BoardSizingViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return numberOfRows
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfColumns
}
func collectionView(_ collectionsiView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Field", for: indexPath) as! FieldCollectionViewCell
cell.tokenView.backgroundColor = .white
cell.tokenView.layer.cornerRadius = (cell.frame.width - 8 * 2) / 2
return cell
}
}
The cells shall keep their size, instead the UICollectionView shall be resized.
Problem: I can't directly set the width and height of a UICollectionView in code, because these are get-only properties. Also if I use
boardSizingCollectionView.frame.size = CGSize(width: FieldCollectionViewCell.frame.width * numberOfColumns, height: FieldCollectionViewCell.frame.height * numberOfRows)
I get an error, because my FieldCollectionViewCell is a CGRect and i don't know how to exactly access the size of a CGRect.
Another hook in the flesh is, that myCollectionView has constraints for it's x and y position, to be auto-positioned on different devices so myCollectionView has to get a width and a height at least in viewDidLoad().
Any hints for me? Thank you very much in forward!