Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 681
sakoaskoaso Avatar asked Feb 26 '26 08:02

sakoaskoaso


1 Answers

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)
}
like image 76
Phyber Avatar answered Feb 28 '26 05:02

Phyber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!