MKodes
MKodes

Reputation: 81

CAShapeLayer path not displayed

I am currently working on a round progress bar, to do so I created a customView. However the shapeLayer is not being displayed. I tried adding a frame to the shapeLayer as well as background colour, however that only showed a rectangle rather than the circularPath I am expecting to see. Any ideas as to what I am doing wrong :thinking:

import UIKit

class CircularProgressBar: UIView {
    override func draw(_ rect: CGRect) {
        setupProgressView()
    }

    private func setupProgressView() {
        let shapeLayer = CAShapeLayer()
        let circularPath = UIBezierPath(arcCenter: center,
                                        radius: 100,
                                        startAngle: 0,
                                        endAngle: 2*CGFloat.pi,
                                        clockwise: true)

        shapeLayer.path = circularPath.cgPath
        shapeLayer.fillColor = UIColor.blue.cgColor
        shapeLayer.strokeColor = UIColor.yellow.cgColor
        shapeLayer.lineWidth = 20

        self.layer.addSublayer(shapeLayer)
    }
}

Upvotes: 1

Views: 767

Answers (1)

Jawad Ali
Jawad Ali

Reputation: 14397

Set shapeLayer Frame

shapeLayer.frame = bounds

And better approach is to not use draw method

import UIKit
 @IBDesignable
 class CircularProgressBar: UIView {

    private lazy var shapeLayer: CAShapeLayer = {
        let shape = CAShapeLayer()
        shape.fillColor = UIColor.blue.cgColor
        shape.strokeColor = UIColor.yellow.cgColor
        shape.lineWidth = 20
        return shape
    }()

    override init(frame: CGRect) {

        super.init(frame: frame)
        addLayers()
    }

    required init?(coder: NSCoder) {

        super.init(coder: coder)
        addLayers()
    }

    private func addLayers() {
        layer.addSublayer(shapeLayer)
    }


    override func layoutSubviews() {
        updatePath()
    }


    private func updatePath() {

        let circularPath = UIBezierPath(arcCenter: CGPoint(x: bounds.midX, y: bounds.midY),
                                        radius: min(bounds.midX, bounds.midY) - shapeLayer.lineWidth/2,
                                        startAngle: 0,
                                        endAngle: 2*CGFloat.pi,
                                        clockwise: true)
        shapeLayer.frame = bounds
        shapeLayer.path = circularPath.cgPath
    }
}

enter image description here

Upvotes: 1

Related Questions