Can I clipToBounds selectively?

116 Views Asked by At

I have a custom class that adds a border to my button and has a function to create the “X” button in the upper lefthand corner.

First problem: In order for the X button to appear outside the bounds of the image button, I have to tun off clipToBounds on the image button. But that has the negative side effect of allowing the image to poke through the rounded corners. Is there a way to clip just the image and not the X button?

Second problem: The border is showing over the X button. (I thought it was an alpha problem at first, but it is not.) I’m hoping the solution to the first problem will solve the second one which is why I’m addressing both here.

enter image description here

2

There are 2 best solutions below

1
On BEST ANSWER

I'd suggest creating a new view and add the x button and image view as subviews. This view will not clip to bounds. Then set the border, corner radius and clipToBounds on the image view.

0
On

My best advice would be to replace your button with a custom UIView which you'll add a UITapGestureRecognizer to. You'll then be able to solve your problem pretty quickly.

In your ButtonView (your UIView subclass) add a UIImageView, with your image and add a border to the UIImageView itself. Then round corners using layer.cornerRadius and clip to bounds.

Now add a separate UIImageView to your ButtonView and bring it to front. Add the 'x' image and round corners as necessary.

Finally set the background image of ButtonView to .clear to top it all off.