Reputation: 3831
I'm trying to render a basic grid of squares in a collection view. I know the number of columns and number of rows I'd like to render. However, I can't work out how to programmatically render the squares.
I have a view controller that looks like this:
class BoardViewController: UIViewController {
@IBOutlet weak var board: UICollectionView!
var game = Game()
override func viewDidLoad() {
super.viewDidLoad()
board.delegate = self
// Do any additional setup after loading the view.
}
}
extension BoardViewController: UICollectionViewDelegateFlowLayout {
}
extension BoardViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return game.getColumns() * game.getRows()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
}
}
I know that I need to use the cellForItemAt method to render the custom cells.
I also have a CustomView (sub of UIView) class like this:
import UIKit
class CustomView: UIView {
override init(frame: CGRect){
super.init(frame: frame)
self.backgroundColor = UIColor.blue
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
and then a BoardGridCell class:
class BoardGridCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView = CustomView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
The Apple docs say:
"To configure the appearance of your cell, add the views needed to present the data item’s content as subviews to the view in the contentView property. Do not directly add subviews to the cell itself. The cell manages multiple layers of content, of which the content view is only one. In addition to the content view, the cell manages two background views that display the cell in its selected and unselected states."
However, whenever I try to set the contentView property, I get "Cannot assign to property: 'contentView' is a get-only property".
So my question is - how do I add subviews to the contentView property?
I'm very new to Swift so I'd really appreciate it if anyone could clarify this for me.
Thanks
Upvotes: 0
Views: 681
Reputation: 353
Did you set size of items ?
in CollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
where value 100 could be some calculated number based on your screen size
Upvotes: 1