bkwebhero bkwebhero - 1 year ago 78
Swift Question

Why are image views sometimes not appearing in collection view cells?

I just updated to Swift 3.

My collection views were working great before the update. I did the recommended changes to make the compiler happy, but now I'm having this problem.

Image views that are in my custom UICollectionViewCells are simply not appearing anymore. Neither programmatically generated image views nor prototype image views are appearing.

I've given the image views background colors to check if my images are nil. The background colors aren't appearing, so it is safe to assume the image views are not appearing at all.

The cells themselves ARE appearing. Each image view has a label underneath, and the label is displaying properly with the correct text.

The most confusing part is that sometimes the image views DO appear, but there seems to be no rhyme or reason as to why or when.

My code is pretty standard, but I'll go ahead and share it anyway:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return searchClubs.count

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell: HomeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell

cell.barLabel.text = searchClubs[indexPath.row].name
cell.imageCell.image = searchClubs[indexPath.row].image

cell.imageCell.layer.masksToBounds = true
cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height / 2

return cell


func feedSearchClubs(child: AnyObject) {

let name = child.value(forKey: "Name") as! String

let base64EncodedString = child.value(forKey: "Image")!
let imageData = NSData(base64Encoded: base64EncodedString as! String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
let image = UIImage(data:imageData! as Data)

//Populate clubs array
let club = Club.init(name: name, image: image!)

DispatchQueue.main.async {

Answer Source

Since Xcode 8 you have to call layoutIfNeeded() to calculate size (in your case you need to know cell.imageCell.frame.height) and position from auto layout rules or use a fixed value of cornerRadius.

cell.imageCell.layer.masksToBounds = true
cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height / 2


cell.imageCell.layer.masksToBounds = true
cell.imageCell.layer.cornerRadius = 5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download