Reputation: 3222
I am programmatically creating a UICollectionViewController
:
class MyCollectionVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {
init() {
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
override func loadView() {
super.loadView()
self.collectionView.delegate = self
...
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let dimension = self.view.bounds/3
return CGSize(width: dimension, height: dimension)
}
override final func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print ("Cell Size: (self.collectionViewLayout as! UICollectionViewFlowLayout).itemSize)
}
}
I need thee actually cell size at cellForItemAt
to do more work.
Cell size above prints out 50 x 50 at all times. This is the default size given. iPhone or iPad, portrait of landscape, it is always 50.
The odd thing is, the actual cell layout gets displayed correctly. Everything else works and looks perfectly.
What am I missing here?
Upvotes: 2
Views: 871
Reputation: 214
Try This
class GridLayout: UICollectionViewFlowLayout {
override init() {
super.init()
self.minimumLineSpacing = 0
self.minimumInteritemSpacing = 0
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepare() {
super.prepare()
guard let collectionView = self.collectionView else {return}
let cellWidth = collectionView.frame.width / 3
self.itemSize = CGSize(width: cellWidth, height: cellWidth) // Your Cell Size
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.collectionViewLayout = GridLayout()
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print((self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your Cell Id", for: indexPath)
return cell
}
Upvotes: 1