Reputation: 979
I am new in Swift and I am facing a problem with collection view. When I am returning 1 in numberOfItemsInSection cellForItemAt not call but when I return 2 it get call. I am not able to understand problem. Delegate and protocol are also correct.
My code is like this:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrSelectedSchoolIds.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = CollectionViewFilter.dequeueReusableCell(withReuseIdentifier: "SchoolLogo", for: indexPath as IndexPath) as! SchoolLogo
cell.imgSchoolLogo.image = getSchoolLogo(schoolID: arrSelectedSchoolIds[indexPath.row])
return cell
}
func getSchoolLogo(schoolID:String?) -> UIImage
{
switch schoolID
{
case "1":
return UIImage(named: "image1")!
case "2":
return UIImage(named: "image2")!
case "3":
return UIImage(named: "image3")!
case "4":
return UIImage(named: "image4")!
case "5":
return UIImage(named: "image5")!
case "6":
return UIImage(named: "image6")!
default:
return UIImage(named: "defaultimage")!
}
}
Images are added in Assest file.
Upvotes: 2
Views: 1321
Reputation: 25423
I've had the exact same problem. My UICollectionView has a height of 16. I could not change it.
I ended up faking a second item. If I'm only having one item return 2 in:
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
In my public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
, I was looking if I'm out of bounds and if so, return the same cell which is just rendering itself blank.
Now my single cell is being shown just fine.
Upvotes: 0
Reputation: 121
I had the same problem. this happened when the collectionView scroll direction is horizontal and the height of collectionView is less than 50. I increased the collectionView height to 50 and the problem solved.
Upvotes: 4
Reputation: 1106
Solution for Swift 5.1
You can try setting up the flowLayout of the collection view as shown below:
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
collectionView.collectionViewLayout = flowLayout
Upvotes: 0
Reputation: 477
The cellForItemAtIndexPath will not get called if you do not provide the content size information to the collection view. If you are using Flow layout, You need to set the item sizes properly.
Upvotes: 1