Problem with circle CAShapeLayer

Hello, I have a one problem.
I have one storyBoard on which collection view.
Cell of Collection View have a UIView.
And later in code I'm add circle on this view, but with time all circles, but first and last is disappeared.
May be somebody can help me.
I from Russia, about my English is soooo bad :)

Look at code of my collection view cell:

import UIKit

class CustomCollectionViewCell: UICollectionViewCell {

static let cellID = "CustomCell"


@IBOutlet weak var BackGroundView: UIView!

var circle : CAShapeLayer? = nil

var cellcreate : CellModel? {
    didSet {
        self.UpdateUI()
    }
}

private func UpdateUI () {
    if let cellcreate = cellcreate {
        BackGroundView.backgroundColor = cellcreate.color
        print("Hello")
    } else {
        BackGroundView.backgroundColor = UIColor.white
    }
}

override func layoutSubviews() {
    super.layoutSubviews()
    
    layer.cornerRadius = 15
    layer.shadowRadius = 10
    layer.shadowOpacity = 0.3
    layer.shadowOffset = CGSize(width: 5, height: 10)
    BackGroundView.clipsToBounds = true
    BackGroundView.layer.cornerRadius = 15
    self.clipsToBounds = false
    
    if circle == nil {
        circle = CAShapeLayer()
        let center = contentView.center
        let cir = UIBezierPath(arcCenter: center, radius: 20, startAngle: 0, endAngle: 2*CGFloat.pi, clockwise: true)
        circle?.path = cir.cgPath
    }
    BackGroundView.layer.addSublayer(circle!)
}

}

1  if circle == nil {
2      circle = CAShapeLayer()
3      let center = contentView.center
4      let cir = UIBezierPath(arcCenter: center, radius: 20, startAngle: 0, endAngle: 2*CGFloat.pi, > clockwise: true)
5      circle?.path = cir.cgPath
6  }
7  BackGroundView.layer.addSublayer(circle!)   <-

You should not be adding circle as a sublayer every time layoutSubviews is called; once is enough.


The problem possibly lies in the positioning of circle inside BackGroundView. Notice that you are positioning circle relative to contentView in lines 3 and 4, but then adding it as a sublayer of BackGroundView, which could have a different center. Your circle could end up being positioned at a completely different place.

If that doesn't help, check if you made any mistakes in sizing or positioning BackGroundView inside contentView.

Terms of Service

Privacy Policy

Cookie Policy