简体   繁体   中英

How do I safely unwrap an instance variable that is used in a function? Swift

I want to safely unwrap the instance variable imageHeight. Inside the func Apply() the variable has a value. But outside the function, the variable has a value of nil. How can pass the value to the instance variable of the class PinterestCell?

Here is the code:

class PinterestCell: UICollectionViewCell {
 
    
    //I want to store the value here ... but i can't, it is always nil. 
    var imageViewHeight: NSLayoutConstraint? 

    override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
            super.apply(layoutAttributes)
            if let attributes = layoutAttributes as? PinterestLayoutAttributes {

                // But it seems like the variable is just stored inside the function ... 
                    imageViewHeight.constant = attributes.imageHeight

                }
            }
}

where you setup your constraint?
imageViewHeight will always nil if you not doing something like this

imageViewHeight = imageView.topAnchor.constraint(equalTo: titleControl.bottomAnchor)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM