iOS: Stretchable Images for Buttons

Apple encourages developers to embrace the borderless look of the buttons. Alas, there are cases where it just doesn’t work – and not just in graphically-intense games. Let’s say you want to build a visual element to represent a custom keyboard or a calculator – it’s hard to imagine it without borders.

If your design is minimalistic and you are satisfied with a simple border and plain background, you can do it programmatically (Interface Builder offers no option to add a border to a button – you could overlay it with a label etc.). But if you want your buttons to look really nice, you probably go to your graphic designer.

Traditionally, you ask your designer for an image of a specific size, you add the image to your button, and voila. When your customer reviews your work, they love it – except… that button needs to be a little bigger. Now you need to ask your designer for a new image.  Not good. What’s more, to get a nice, consistent look, all the buttons should look alike, regardless of their size. Or, you may want to scale your buttons based on the constraints. More images?

Starting with iOS 7 (the deployment target has to be iOS 7+), there is a better way: image slicing. It’s a feature of an asset catalog that lets you specify which area of an image should be stretched (or tiled) when the bounds require it, and which should remain unchanged (end caps). You can define horizontal or vertical stretching, or both.

Steps:

  1. Select your asset catalog. Select the set and the image to slice.
  2. Click “Show Slicing” at the bottom (or Editor | Show Slicing).
  3. Click “Start Slicing” displayed over the image.
  4. Adjust areas by dragging slicing handles, or in the Attributes inspector.

This feature is easy to use and provides a good reusability of graphic resources, especially for buttons with rounded corners. Once your image is sliced, set it as a background image on your button.

Reference: Xcode Help | Work with assets | Add a resizable area to an image