I have a collection View with an image in each collectionViewCell. I want to have only 3 cells for any given frame/ screen size. How do I implement this. I have written some code based on this post
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let numberOfCell = 3
let cellWidth: CGFloat = [[UIScreen mainScreen].bounds].size.width/numberOfCell
return CGSizeMake(cellWidth, cellWidth)
}
But its not working and giving an error. What is the best way to do this.
Here's a WWDC video demoing this technique. class MyLayout: UICollectionViewFlowLayout { override func prepare() { super. prepare() guard let collectionView = collectionView else { return } itemSize = CGSize(width: ..., height: ...) } }
Here is your swift code:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat
let cellWidth = UIScreen.mainScreen().bounds.size.width / numberOfCell
return CGSizeMake(cellWidth, cellWidth)
}
Here the type of numberOfCell
must be a CGFloat
because UIScreen.mainScreen().bounds.size.width
return a CGFloat
value so if you want to divide it with numberOfCell
then type numberOfCell
must be CGFloat
because you can not divide CGFloat
with Int
.
Here is Swift 3 code and you to have implement UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat
let cellWidth = UIScreen.main.bounds.size.width / numberOfCell
return CGSize(width: cellWidth, height: cellWidth)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With