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
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.
by default, the UIView create programaticly has translatesAutoresizingMaskIntoConstraints = true, change it to false to enable auto layout :