Search code examples
iosswiftuiviewrounded-cornerscashapelayer

UIView has different cornerRadius than CAShapeLayer


I want to add a background view to a UITableViewCell, and also a CAShapeLayer to act as a border around the background view (I will need a dashed border).

My problem is however, even though I set the cornerRadius of the view and the layer to the same value, they render completely differently.

enter image description here

Does anyone have a clue what's going on?

The code:

final class Cell: UITableViewCell {

    private let borderLayer = CAShapeLayer()
    private let _backgroundView = UIView()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // Add a blue background view.
        contentView.insertSubview(_backgroundView, at: 0)
        _backgroundView.backgroundColor = .blue
        _backgroundView.layer.cornerRadius = 28

        // Add the border layer.
        borderLayer.fillColor = nil
        borderLayer.strokeColor = UIColor.red.cgColor
        borderLayer.lineWidth = 2
        contentView.layer.addSublayer(borderLayer)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // Update the frames.
        _backgroundView.frame = contentView.bounds
        borderLayer.path = UIBezierPath(roundedRect: contentView.bounds, cornerRadius: _backgroundView.layer.cornerRadius).cgPath
    }
}

A Playground Gist to reproduce it

Any help is appreciated!


Solution

  • Building the path from a CGPath directly seems to solve the problem.

    borderLayer.path = CGPath(roundedRect: contentView.bounds, cornerWidth: _backgroundView.layer.cornerRadius,
                              cornerHeight: _backgroundView.layer.cornerRadius, transform:  nil)