How to create border in UIButton?

You can set the border properties on the CALayer by accessing the layer property of the button.

First, add Quartz

#import <QuartzCore/QuartzCore.h>

Set properties:

myButton.layer.borderWidth = 2.0f;
myButton.layer.borderColor = [UIColor greenColor].CGColor;

See:

https://developer.apple.com/documentation/quartzcore/calayer#//apple_ref/occ/cl/CALayer

The CALayer in the link above allows you to set other properties like corner radius, maskToBounds etc...

Also, a good article on button fun:

https://web.archive.org/web/20161221132308/http://www.apptite.be/tutorial_custom_uibuttons.php


Its very simple, just add the quartzCore header in your file(for that you have to add the quartz framework to your project)

and then do this

[[button layer] setCornerRadius:8.0f];

[[button layer] setMasksToBounds:YES];

[[button layer] setBorderWidth:1.0f];

you can change the float values as required.

enjoy.


Here's some typical modern code ...

self.buttonTag.layer.borderWidth = 1.0f;
self.buttonCancel.layer.borderWidth = 1.0f;

self.buttonTag.layer.borderColor = [UIColor blueColor].CGColor;
self.buttonCancel.layer.borderColor = [UIColor blueColor].CGColor;

self.buttonTag.layer.cornerRadius = 4.0f;
self.buttonCancel.layer.cornerRadius = 4.0f;

that's a similar look to segmented controls.

UPDATE for Swift:

  • No need to add "QuartzCore"

Just do:

button.layer.cornerRadius = 8.0
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.black.cgColor