Search code examples
swiftuicollectionviewcell

centerX and Y contraints not correct with UICollectionViewCell


I am making a custom UICollectionViewCell, but when I want to center a view inside the default contentView with constraints (programmatically), it is displaying a random position.

Here's my code:

NSLayoutConstraint.activate([
  merchantContentView.heightAnchor.constraint(equalToConstant: 150.0),
  merchantContentView.widthAnchor.constraint(equalToConstant: 335),
  merchantContentView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
  merchantContentView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
])

And here's a screenshot: screenshot

The UICollectionViewCell's contentView is in black and the another view in blue.

What am I missing? I am using Xcode 9.0 beta 5 (9M202q), with the iOS 11 SDK.


Solution

  • I just solved it myself. My mistake that I set the translatesAutoresizingMaskIntoConstraints to false for the contentView, which is totally understandable now :)

    So I just removed the following line:

    contentView.translatesAutoresizingMaskIntoConstraints = false