I'm building an app using swift in the latest version of Xcode 6, and would like to know how I can modify my button so that it can have a rounded border that I could adjust myself if needed. Once that's done, how can I change the color of the border itself without adding a background to it? In other words I want a slightly rounded button with no background, only a 1pt border of a certain color.
16 Answers
To do this job in storyboard (Interface Builder Inspector)
With help of IBDesignable
, we can add more options to Interface Builder Inspector for UIButton
and tweak them on storyboard. First, add the following code to your project.
@IBDesignable extension UIButton {
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
@IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
Then simply set the attributes for buttons on storyboard.
I have created a simple UIButton sublcass that uses the tintColor
for its text and border colours and when highlighted changes its background to the tintColor
.
class BorderedButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.borderWidth = 1.0
layer.borderColor = tintColor.CGColor
layer.cornerRadius = 5.0
clipsToBounds = true
contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
setTitleColor(tintColor, forState: .Normal)
setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
setBackgroundImage(UIImage(color: tintColor), forState: .Highlighted)
}
}
This makes use of a UIImage extension that creates an image from a colour, I found that code here: https://stackoverflow.com/a/33675160
It works best when set to type Custom in interface builder as the default System type slightly modifies the colours when the button is highlighted.
This class is based from all the comments and suggestions in answers, and also can be designable directly from xcode. Copy to your project and insert any UIButton and change to use custom class, now just select border or background color from xcode for normal and/or highlighted states.
//
// RoundedButton.swift
//
import UIKit
@IBDesignable
class RoundedButton:UIButton {
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
//Normal state bg and border
@IBInspectable var normalBorderColor: UIColor? {
didSet {
layer.borderColor = normalBorderColor?.CGColor
}
}
@IBInspectable var normalBackgroundColor: UIColor? {
didSet {
setBgColorForState(normalBackgroundColor, forState: .Normal)
}
}
//Highlighted state bg and border
@IBInspectable var highlightedBorderColor: UIColor?
@IBInspectable var highlightedBackgroundColor: UIColor? {
didSet {
setBgColorForState(highlightedBackgroundColor, forState: .Highlighted)
}
}
private func setBgColorForState(color: UIColor?, forState: UIControlState){
if color != nil {
setBackgroundImage(UIImage.imageWithColor(color!), forState: forState)
} else {
setBackgroundImage(nil, forState: forState)
}
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = layer.frame.height / 2
clipsToBounds = true
if borderWidth > 0 {
if state == .Normal && !CGColorEqualToColor(layer.borderColor, normalBorderColor?.CGColor) {
layer.borderColor = normalBorderColor?.CGColor
} else if state == .Highlighted && highlightedBorderColor != nil{
layer.borderColor = highlightedBorderColor!.CGColor
}
}
}
}
//Extension Required by RoundedButton to create UIImage from UIColor
extension UIImage {
class func imageWithColor(color: UIColor) -> UIImage {
let rect: CGRect = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), false, 1.0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Based on @returntrue answer I managed to implement it in Interface Builder.
To get round corners button using Interface Builder add a Key Path = "layer.cornerRadius"
with Type = "Number"
and Value = "10"
(or other value as required) in the "User Defined RunTime Attribute
" of the Identity Inspector
of the button.
You can use this subclass of UIButton to customize UIButton as per your needs.
visit this github repo for reference
class RoundedRectButton: UIButton {
var selectedState: Bool = false
override func awakeFromNib() {
super.awakeFromNib()
layer.borderWidth = 2 / UIScreen.main.nativeScale
layer.borderColor = UIColor.white.cgColor
contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
override func layoutSubviews(){
super.layoutSubviews()
layer.cornerRadius = frame.height / 2
backgroundColor = selectedState ? UIColor.white : UIColor.clear
self.titleLabel?.textColor = selectedState ? UIColor.green : UIColor.white
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
selectedState = !selectedState
self.layoutSubviews()
}
}
I think the easiest and the cleanest way, is to use protocol to avoid inherit and code repetition. You can change this properties directly from storyboard
protocol Traceable {
var cornerRadius: CGFloat { get set }
var borderColor: UIColor? { get set }
var borderWidth: CGFloat { get set }
}
extension UIView: Traceable {
@IBInspectable var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set {
layer.masksToBounds = true
layer.cornerRadius = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
guard let cgColor = layer.borderColor else { return nil }
return UIColor(cgColor: cgColor)
}
set { layer.borderColor = newValue?.cgColor }
}
@IBInspectable var borderWidth: CGFloat {
get { return layer.borderWidth }
set { layer.borderWidth = newValue }
}
}
Update
In this link you can find an example with the utility of Traceable protocol
as aside tip make sure your button is not subclass of any custom class in story board , in such a case your code best place should be in custom class it self cause code works only out of the custom class if your button is subclass of the default UIButton class and outlet of it , hope this may help anyone wonders why corner radios doesn't apply on my button from code .
import UIKit
@IBDesignable
class RoundedButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 8
@IBInspectable var borderColor: UIColor? = .lightGray
override func draw(_ rect: CGRect) {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
layer.borderWidth = 1
layer.borderColor = borderColor?.cgColor
}
}
Solution for UIBuilder lovers:
check the 'Clip to Bounds' checkbox in the UIButton's "Attribution Inspector" window. [see figure 1 below]
Click on the "Identity Inspector", and hit the '+' symbol to enter a new Key Path: layer.cornerRadius, Number, 8 (or 16 etc...). [see figure 2 below]
You can subclass UIButton
and add @IBInspectable
variables to it so you can configure the custom button parameters via the StoryBoard "Attribute Inspector". Below I write down that code.
@IBDesignable
class BHButton: UIButton {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBInspectable lazy var isRoundRectButton : Bool = false
@IBInspectable public var cornerRadius : CGFloat = 0.0 {
didSet{
setUpView()
}
}
@IBInspectable public var borderColor : UIColor = UIColor.clear {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable public var borderWidth : CGFloat = 0.0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
// MARK: Awake From Nib
override func awakeFromNib() {
super.awakeFromNib()
setUpView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setUpView()
}
func setUpView() {
if isRoundRectButton {
self.layer.cornerRadius = self.bounds.height/2;
self.clipsToBounds = true
}
else{
self.layer.cornerRadius = self.cornerRadius;
self.clipsToBounds = true
}
}
}