Search code examples
iosswiftuicollectionviewcell

Check if variable is nil from UICollectionViewCell subclass


I have got this UICollectionViewcell

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell

    if let CurrentPost = posts[indexPath.row] as? Post {
        if(CurrentPost.PostImage == nil) {
            print(CurrentPost.PostText)
        }
    }

    return cell
}

class PostCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        designCell()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    let postImage: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.contentMode = .scaleAspectFill
        return v
    }()

    func designCell() {
        addSubview(postImage)

        if (postImage.image == nil) {
            print("ss")
        }

        cellConstraints()
    }
}

Now what I want to do is to check is at posts[indexPath.row] the PostImage is nil or not. If it is nil then at PostCell I want to print "ss", otherwise I want to set postImage's image to PostImage.


Solution

  • Inside your cell:

    func passImage(imageToSet: UIImage?){
        if let image = imageToSet{
            //Do whatever you want
        }else{
            print("ss")
        }
    }
    

    In your VC

    if let CurrentPost = posts[indexPath.row] as? Post{
        cell.passImage(imageToSet: CurrentPost.PostImage)
    }