styler1972 styler1972 - 6 months ago 78
Swift Question

Masking multiple iOS UIViews with a single UIView

Is it not possible to have a UIView be a maskedView to more than 1 view? I'm setting the maskView on the following UIViews, but only the last one retains the mask setting.

imageOne.maskView = viewMask
labelThing.maskView = viewMask
labelOtherThing.maskView = viewMask
labelLastThing.maskView = viewMask
labelMaskThis.maskView = viewMask //the only masked view


Troubleshooting this, I commented out the last line, and confirmed my suspicions.

imageOne.maskView = viewMask
labelThing.maskView = viewMask
labelOtherThing.maskView = viewMask
labelLastThing.maskView = viewMask //now gets the mask
//labelMaskThis.maskView = viewMask


Is there a way for my
viewMask: UIView
to be applied to more than 1 view?

Answer

Looks like the answer is no, you can't use the same UIView instance to mask multiple views: apparently the masking view's layer is being integrated into the layer hierarchy of the view that is being masked.

The best way would be to create a new UIView mask instance for each of the views you are trying to mask. Alternatively you could copy the existing view via NSKeyedArchiver:

let archivedData = NSKeyedArchiver.archivedDataWithRootObject(viewMask)
let viewMaskCopy = NSKeyedUnarchiver.unarchiveObjectWithData(archivedData) as! UIView

Although I would suggest simply creating new masking views instances the way you instantiated viewMask in the first place.

You may also group the masked views in a containing UIView in storyboard, and apply the mask to that view instead.