Search code examples
iosswiftuibezierpathcashapelayer

How to change stroke color of CAShaperLayer on button click


I am have create some custom layer and added on UIView ,i have two CAShaper Layer but i am just showing only one example here

    hexBorderOtline = CAShapeLayer()
    hexBorderOtline.name = "dhiru_border_hidden"
    hexBorderOtline.path = path2.cgPath
    hexBorderOtline.lineCap = .round  
    hexBorderOtline.strokeColor = inActiveBorderColor.cgColor
    hexBorderOtline.fillColor = UIColor.clear.cgColor
    self.layer.addSublayer(hexBorderOtline)

I want to change it's border color when button is clicked.

func btnAction()
{
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
}

But this is not working , i am posting one reference image what i need to do on button click .

enter image description here


Solution

  • Your method of toggling the shape layer’s stroke color is correct:

    enter image description here

    All I’m doing is:

    var enabled = false
    
    @IBAction func didTapButton(_ sender: Any) {
        enabled = !enabled
        hexBorderOtline.strokeColor = enabled ? activeBorderColor.cgColor : inActiveBorderColor.cgColor
    }
    

    So, your problem rests elsewhere. For example:

    • Perhaps you have another shape layer that is on top of the one for which you’re changing color.

    • Or perhaps your ivar, is pointing to another shape layer.

    • Or perhaps your button isn’t hooked up to your btnAction routine (the absence of any @IBAction or @objc makes me suspect you’re not calling this routine).

    It’s going to be something simple like that.

    I’d suggest you add print(hexBorderOtline) where you create the CAShapeLayer and again in the btnAction and confirm that both:

    1. You are seeing both sets of print statements; and

    2. They are printing the same memory address associated with the shape layer (i.e. make sure they are they referring to the same shape layer).

    But it’s got to be something like that. This is the correct way to change strokeColor and that will update the shape layer automatically for you. Your problem rests elsewhere.