Search code examples
swiftautolayoutuicollectionviewcelldrawuicollectionviewlayout

Proper Timing to Draw Circles using Autolayout inside UICollectionView


Inside each collection view cell I have a view which I'd like to make a perfect circle. I'm basing the width of the cells on the main views width using Autolayout.

My problem: some of the views don't have a perfect circle. I'm guessing its a conflict in timing, that I don't have the main views bounds set yet before making these UIViews into circles. Should I draw the cornerRadius at a specific time? Everything else works fine. Thanks!

func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize {
    return CGSize(width: self.view.frame.width/3, height: 400)
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let sessionCell = (collectionView.dequeueReusableCell(withReuseIdentifier: Storyboard.cellID, for: indexPath)) as? DayCollectionViewCell {
        sessionCell.circleView.layer.cornerRadius = sessionCell.circleView.frame.width/2
        return sessionCell
    }
}

Solution

  • You need to set it here

    override func layoutSubviews() {
      super.layoutSubviews()
      self.circleView.layer.cornerRadius = self.circleView.frame.width/2
    }
    

    Inside DayCollectionViewCell class