The output is UICollectionViewCell nil in the class, but works after using dequeueReusableCellWithReuseIdentifier

There are several messages on nil outputs in the UICollectionViewCell class, for example this and, but none of these solutions worked. The use of a strong outlet instead of a weak one refused, the solution is registerClassnot applied, since the cell does not use a custom XIB, data sources and delegates are connected correctly, etc.

In this case, the output is a UIImageView, which is zero when accessed inside the UICollectionViewCell class, but works fine when accessed from the outside.

UICollectionView Code:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(AlbumCellIdentifier, forIndexPath: indexPath) as! AlbumCell

    cell.imageView.image = getThumbnail()
    cell.imageView.contentMode = .ScaleAspectFill        
    cell.imageView.layer.masksToBounds = true
    cell.imageView.layer.cornerRadius = cell.frame.size.width / 2

    return cell
}

UICollectionViewCell Code:

class AlbumCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!

    override init(frame: CGRect) {
        super.init(frame: frame)

        doInit(frame)
    }


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        doInit(frame)
    }


    private func doInit(frame: CGRect) {
        // Round corners
        imageView.layer.masksToBounds = true
        imageView.layer.cornerRadius = frame.size.width / 2
    }
}

UICollectionViewCell , imageView , UICollectionView , imageView, , .

imageView nil UICollectionViewCell?

+4
1

, doInit awakeFromNib, , , , ( ):

override func awakeFromNib() {
  super.awakeFromNib()
  doInit(frame)
}

cornerRadius , layoutSubviews, :

override func awakeFromNib() {
  super.awakeFromNib()
  imageView.layer.masksToBounds = true
}

override func layoutSubviews() {
  super.layoutSubviews()
  imageView.layer.cornerRadius = frame.size.width / 2
}

. , nib , imageView.layer.masksToBounds = true init(frame: CGRect) awakeFromNib.

+3

All Articles