How to add label or text in to CAShapeLayer

roledene JKS picture roledene JKS · Jan 27, 2016 · Viewed 12k times · Source

Here is my class and it'll draw a circle, it looks like this:

enter image description here

    class OvalLayer: CAShapeLayer {

    let animationDuration: CFTimeInterval = 0.3

    override init() {
        super.init()
        fillColor = Colors.green.CGColor
        path = ovalPathSmall.CGPath
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    var ovalPathStart: UIBezierPath {
        let path = UIBezierPath(ovalInRect: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))

        return path
    }
}

Now I need to add a text to middle of this circle, I tried to find it on google but nothing that works fine. I am not sure if it's possible or not, can anyone help me if it's possible?

Answer

arrteme picture arrteme · Jan 27, 2016

I guess you should add CATextLayer as a sublayer to CALayer... That works fine that way: try adding CAShapeLayer first, and then CATextLayer (to same CALayer parent layer), for example in following order...

// assume self - is UIView instance

self.layer.addSublayer(shapedLayer) // shapedLayer - CAShapeLayer instance
self.layer.addSublayer(textLayer) // textLayer - CATextLayer instance