Search code examples
swiftuicollectionviewautolayoutuicollectionviewcell

After setting custom UICollectionViewCell.contentview.translatesAutoresizingMaskIntoConstraints = false, autolayout is not working


  1. I made a custom collectionview cell in storyboard.
  2. I added a button to collectionview cell, and set autolayout (0,0,0,0) to cell.
  3. I made a custom collectionviewcell class. At this class, I set cell's contentview.translatesAutoresizingMaskIntoConstraints = false
  4. Cell's button's autolayout is not working!

    class SomeCell: UICollectionViewCell {    
       override init(frame: CGRect) {
         super.init(frame: frame)
         self.setup()
       }
    
    
       required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
         self.setup()
       }
    
       func setup() {
         self.contentView.translatesAutoresizingMaskIntoConstraints = false
       }
    
    }
    

code of ViewController

layout in StoryBoard

Simulator: Button's autolayout is missed


Solution

  • I took a look at all constraints during runtime, and compared when translatesAutoresizingMaskIntoConstraints is set to false and true.
    The result is that the cell's content view is not getting their height and width autolayout constraint when translatesAutoresizingMaskIntoConstraints is set to false. In your case, this leads to ambiguous layout
    As to why this is the case, I'm guessing that implementation of UICollectionFlowLayout relies on that property being set to true, but I couldn't find any documentation about this.