Masking multiple iOS UIViews with a single UIView

2019-05-28 18:48发布

问题:

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?

回答1:

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.



标签: ios swift uiview