Search code examples
iosuicontrol

How do I change the size of a UIControl when highlighted?


I have a UIControl subclass that changes appearance and size when touched, a bit like the button of an iOS keyboard turns into the typewriter hand when touched:

keyboard sample

I’m not sure how to write it. The idea is to draw a different shape when the default button shape is highlighted:

                    +---+
                    |   |
+---+               |   |
|   |  -> touch ->  |   | 
+---+               +---+

But since the default button is smaller than the highlighted shape, the bigger shape gets clipped. I have considered these options:

  • Drawing outside the default frame. Does not seem to be possible.
  • Changing the size of the control when highlighted. Feels quite hacky and error-prone.
  • Enlarging the control to accomodate the larger shape. Feels “wrong”, I’d like to be able to work with the control in its smaller, default shape.

Is there a best practice for this scenario?


Solution

  • Here are a few approaches:

    1. You can draw outside the frame, you just have to make sure that myView.clipsToBounds is False. This would allow you to draw outside the bounds of the view inside another view and draw whatever extra content you would like.

    2. That is probably the cleanest solution, but is also a bit "hacky" in my opinion. The other approach would be dirty (as you said) and to reset the frame size.

    3. The last approach would be to create another view (the key pressed down) and throw it on top of the original (unpressed key) view.

    All in all, it really comes down to what you're drawing / showing inside your view.