0

When I try to copy an object from a Custom Layer Class I have created, the copy created matches the original, but the original loses its mask.

In order to perform the copy, I have created an extension of my custom class:

extension CustomLayer: NSCopying {

    func copy(with zone: NSZone? = nil) -> Any {
        let clone = CustomLayer()

        // Type Properties
        clone.colorFill             = self.colorFill
        clone.colorMap              = self.colorMap
        clone.radius                = self.radius

        // LayerProperties
        clone.frame                 = self.frame
        clone.cornerRadius          = self.cornerRadius
        clone.opacity               = self.opacity
        clone.position              = self.position

        clone.shadowRadius          = self.shadowRadius
        clone.shadowColor           = self.shadowColor
        clone.shadowOffset          = self.shadowOffset
        clone.shadowOpacity         = self.shadowOpacity
        clone.shadowPath            = self.shadowPath 

        clone.mask                  = self.mask

        return clone
    }
}

I then create a copy this way:

let originalLayer = CustomLayer()
...
view.layer.addSublayer(originalLayer)

let copyLayer = originalLayer.copy() as! CustomLayer
view.layer.addSublayer(copyLayer)

As you can see from the screenshot, the original layer does not have a mask anymore whilst the copy has it.

Top: original layer / Bottom: copy layer

I have used this method in the past for other Custom Layer Class and I have never encountered this issue until now. I have also tried create a CALayer that is an instance of self.mask and then applies it as a mask to the copy, but the result is the same.

Any pointers would be greatly appreciated!

Thanks in advance for your time!

Chris
  • 305
  • 1
  • 12

1 Answers1

0

My intuition tells me that you probably have to copy the mask in your copy implementation. I found this question that supports my intuition.

Can a single CALayer be used as the mask for multiple other layers?

Joe VB
  • 51
  • 3
  • Thanks for your reply @Joe . In the thread you indicate, it says to use the same CA Layer as masks for multiple layers, therefore I can see why it does not work. Here I am already inside a copy method and I fail to connect the dots. Furthermore as soon as I use `self.mask` even if I do not attach it to the clone layer mask (let's say I create another `CALayer` and sets it to `self.mask`), the original copy sets its mask to `nil`. Last but not least, the copy method I use works for other custom classes whereas according to the thread it then should not work at all... Hence why I am puzzled. – Chris Dec 30 '18 at 10:30