Subview frame is incorrect when creating UICollectionViewCell Subview frame is incorrect when creating UICollectionViewCell ios ios

Subview frame is incorrect when creating UICollectionViewCell


You can get the final frames of your cell by overriding layoutIfNeeded() in your custom Cell class like this:

override func layoutIfNeeded() {    super.layoutIfNeeded()    self.subView.layer.cornerRadius = self.subView.bounds.width / 2}

then in your UICollectionView data Source method cellForRowAtIndexPath: do this:

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CustomCollectionViewCellcell.setNeedsLayout()cell.layoutIfNeeded()


I had the same issue with a UICollectionViewCell using auto layout constraints.

I had to call layoutIfNeeded before I was configuring my subview that relied on the views frame width.


Had this issue with Core Graphics drawing in iOS 10, Swift 3.0.1.

Add this method to UICollectionView subclass:

override func didMoveToSuperview() {    super.didMoveToSuperview()    setNeedsLayout()    layoutIfNeeded()}

My problem was that Core Graphics shapes were not calculated properly, because a layoutSubviews() wasn't called.