/ objectivec

Bordered Slicing in Xcode

This is another small blogpost about how I solved a little issue. This time it's about borded buttons, rounded corners and slicing.

First things first: I got a new job as — surprise 🎉 — iOS developer and it's much, much better than the previous one. Let's hope, that it lasts much longer than six weeks.

Now, back to topic: In my rare spare time, I'm still working on the small app I mentioned last time. This app features some buttons and I want them to have a border with rounder corners. They should look like this one:


The pretty standard approach would be something like this in code, as Storyboards don't support borders with rounder corners without additional work:

self.punchNazisButton.layer.borderWidth =2;
self.punchNazisButton.layer.cornerRadius = 10;
self.punchNazisButton.layer.borderColor = [UIColor fancyBlueColor].CGColor;

I went that way, but an issue appeared: When a user taps this button, the title color changes, but border color stays the same. This looks weird:


A while ago I saw a "What's new in Xcode"-video or something like that and in this video, slicing was introduced. And somehow, I remembered this video and slicing.

Slicing means basically, that you tell iOS to use certain parts of an image just like they are and to resize those in between. You could do bordered buttons with rounded corners pretty easily: You want the corners to be rounded, but straight lines between these corners. So you tell iOS to use the corners, but to strech/resize/... the straight lines in between. Becky Hansmeyer wrote a short piece about it a while ago.

So I gave it a try: I exported the border from the Sketch-File as 1x, 2x and 3x-assets and imported them right away into my Xcode asset catalogue. The exported/imported assets looked like this:


Then, I had to tell iOS, what to do with each area. I selected an image, scrolled down in the "Attributes Inspector", until I saw the "Slicing"-area. I had to set left and right values for 1x, 2x and 3x separately:


Xcode also features a GUI for slicing, which you can use to set left, right and width visually:


Afterwards I set this image as backgroundImage in my storyboard — shame on me, in this project I'm using a single Main.storyboard — and that's it. If I tap on the "Punch Nazis"-button now, the border has the some color as the title:


Bordered Slicing in Xcode
Share this