Unable to programatically align UIImageView to the centre of UICollectionViewCell

76 views Asked by At

Currently, I have a UICollectionViewCell used in horizontal scroll UICollectionView. I have tried the following to centre the icon to the centre.

class BasicCell: UICollectionViewCell {
    
    var tabInfo: TabInfo?
    
    let imageView: UIImageView = {
        let image = UIImage(systemName: "gear")
        let imageView = UIImageView(image: image)
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(imageView)

        // Hoping we can center imageView. But it would not work? Why?
        addConstraint(NSLayoutConstraint.init(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint.init(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))

        BasicCell.topRoundCorners(self.contentView)
    }

Here's the outcome

enter image description here

I expect the following code can centre the UIImageView without issue. However, it doesn't help

addConstraint(NSLayoutConstraint.init(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint.init(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))

At first, I was thinking to give up the programatically way, and create UI layout via storyboard. However, in my storyboard, there is no UICollectionViewController. (The top tab bar component, is a UIView holding a UICollectionView created programatically).

Without UICollectionViewController, I don't find a way to drag and drop a UICollectionViewCell into the storyboard.

Do you have any idea, how I can centre my UIImageView, with correct programatically code? Or, should I try to fix this problem with XIB? Thanks.

2

There are 2 answers

0
goat_herd On BEST ANSWER

by default, the UIView create programaticly has translatesAutoresizingMaskIntoConstraints = true, change it to false to enable auto layout :

       imageView.translatesAutoresizingMaskIntoConstraints = false
        let iamgeViewConstraints = [
            imageView.centerXAnchor.constraint(equalTo: centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: centerYAnchor)
        ]
        NSLayoutConstraint.activate(iamgeViewConstraints)
0
Kishan Bhatiya On

Try to set imageView.translatesAutoresizingMaskIntoConstraints = false that tells iOS not to create auto layout constraints programmatically. Also, you can set constraints using frame like

imageView.frame = CGRect(x: superView.frame.width / 2, y: superView.frame.height / 2, width: imageViewWidth, height: imageViewHeight)

then you don't require imageView.translatesAutoresizingMaskIntoConstraints = false