iPhone
iPhone

Reputation: 4170

How to create border in UIButton?

I use custom button in my app named "addButton" and I want to border it with white color how can i get the white color border around my custom button?

Upvotes: 182

Views: 191993

Answers (14)

alobaili
alobaili

Reputation: 904

In iOS 15 or above, you can make use of UIButton.Configuration APIs.

Here's sample code in Swift that adds a white border to the button:

var configuration = UIButton.Configuration.plain()
configuration.title = "Example"
configuration.background.strokeWidth = 1
configuration.background.strokeColor = .white

let button = UIButton(configuration: configuration)

To make the border respond to button states, such as the highlighted state, assign a closure to the configurationUpdateHandler property of the button.

Here's sample code where I used a UIConfigurationColorTransformer to add a 50% opacity to the border color when the button is highlighted:

button.configurationUpdateHandler = { button in
    let strokeColorTransformer = UIConfigurationColorTransformer { inputColor in
        switch button.state {
            case .highlighted: inputColor.withAlphaComponent(0.5)
            default: inputColor
        }
    }

    button.configuration?.background.strokeColorTransformer = strokeColorTransformer
}

Upvotes: 0

Sharif Rafi
Sharif Rafi

Reputation: 56

(Swift 5) You can add this extension as a common method to create and customize any kind of UIView / UIImage / UIButton.

extension UIView {
    func makeViewBorderStyle(cornerRadius: CGFloat = 8, borderWidth: CGFloat = 1, color: UIColor = UIColor.lightGray){
        self.layer.cornerRadius = cornerRadius
        self.layer.borderWidth = borderWidth
        var borderColor = color
        if borderColor == UIColor.lightGray{
            if #available(iOS 13.0, *) {
                borderColor = UIColor.systemGray3
            } else {
                borderColor = UIColor.lightGray
            }
        }
        self.layer.borderColor = borderColor.cgColor
    }
}

You just need to call the common method like this -->

@IBOutlet weak private var submitButton: UIButton!

override func viewDidLoad() {
        self.submitButton.makeViewBorderStyle()
    }

If you want to customize the border, you just need to pass the value you want like -->

self.submitButton.makeViewBorderStyle(cornerRadius: 12, borderWidth: 2, color: .red)

Upvotes: 1

Ben Packard
Ben Packard

Reputation: 26476

Here's a UIButton subclass that supports the highlighted state animation without using images. It also updates the border color when the view's tint mode changes.

class BorderedButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = tintColor.cgColor
        layer.borderWidth = 1
        layer.cornerRadius = 5

        contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func tintColorDidChange() {
        super.tintColorDidChange()

        layer.borderColor = tintColor.cgColor
    }

    override var isHighlighted: Bool {
        didSet {
            let fadedColor = tintColor.withAlphaComponent(0.2).cgColor

            if isHighlighted {
                layer.borderColor = fadedColor
            } else {
                layer.borderColor = tintColor.cgColor

                let animation = CABasicAnimation(keyPath: "borderColor")
                animation.fromValue = fadedColor
                animation.toValue = tintColor.cgColor
                animation.duration = 0.4
                layer.add(animation, forKey: nil)
            }
        }
    }
}

Usage:

let button = BorderedButton(style: .System) //style .System is important

Appearance:

enter image description here

enter image description here

Upvotes: 7

Fahim Rahman
Fahim Rahman

Reputation: 227

Swift 5

button.layer.borderWidth = 2

To change the colour of the border use

button.layer.borderColor = CGColor(srgbRed: 255/255, green: 126/255, blue: 121/255, alpha: 1)

Upvotes: 5

Ajeet Pratap Maurya
Ajeet Pratap Maurya

Reputation: 4254

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

Upvotes: 53

tong
tong

Reputation: 731

And in swift, you don't need to import "QuartzCore/QuartzCore.h"

Just use:

button.layer.borderWidth = 0.8
button.layer.borderColor = (UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )).cgColor

or

button.layer.borderWidth = 0.8
button.layer.borderColor = UIColor.grayColor().cgColor

Upvotes: 25

BHUVANESH MOHANKUMAR
BHUVANESH MOHANKUMAR

Reputation: 2777

This can be achieved in various methods in Swift 3.0 Worked on Latest version August - 2017

Option 1:

Directly assign the borderWidth property values for UI Button:

  btnUserButtonName.layer.borderWidth = 1.0

Set Title with Default Color values for UI Button:

btnUserButtonName.setTitleColor(UIColor.darkGray, for: .normal)

Set Border with Default Color for the border property values for UI Button:

btnUserButtonName.layer.borderColor = UIColor.red

Set user defined Color for the border property values for UI Button:

   let myGrayColor = UIColor(red: 0.889415, green: 0.889436, blue:0.889424, alpha: 1.0 )
   btnUserButtonName.layer.borderColor = myGrayColor.cgColor

Option 2: [Recommended]

Use the Extension method, so the Button through out the application will be looking consistent and no need to repeat multiple lines of code every where.

//Create an extension class in any of the swift file

extension UIButton {
func setBordersSettings() {
        let c1GreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = 5.0
        self.layer.borderColor = c1GreenColor.cgColor
        self.setTitleColor(c1GreenColor, for: .normal)
        self.layer.masksToBounds = true
    }
}

Usage in code:

//use the method and call whever the border has to be applied

btnUserButtonName.setBordersSettings()

Output of Extension method Button:

enter image description here

Upvotes: 8

bryanmac
bryanmac

Reputation: 39296

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

Upvotes: 364

jaiswal Rajan
jaiswal Rajan

Reputation: 4661

****In Swift 3****

To create border

 btnName.layer.borderWidth = 1
 btnName.layer.borderColor = UIColor.black.cgColor

To make corner rounded

 btnName.layer.cornerRadius = 5

Upvotes: 3

LaloLoop
LaloLoop

Reputation: 2143

Here's an updated version (Swift 3.0.1) from Ben Packard's answer.

import UIKit

@IBDesignable class BorderedButton: UIButton {

    @IBInspectable var borderColor: UIColor? {
        didSet {
            if let bColor = borderColor {
                self.layer.borderColor = bColor.cgColor
            }
        }
    }

    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            self.layer.borderWidth = borderWidth
        }
    }

    override var isHighlighted: Bool {
        didSet {
            guard let currentBorderColor = borderColor else {
                return
            }

            let fadedColor = currentBorderColor.withAlphaComponent(0.2).cgColor

            if isHighlighted {
                layer.borderColor = fadedColor
            } else {

                self.layer.borderColor = currentBorderColor.cgColor

                let animation = CABasicAnimation(keyPath: "borderColor")
                animation.fromValue = fadedColor
                animation.toValue = currentBorderColor.cgColor
                animation.duration = 0.4
                self.layer.add(animation, forKey: "")
            }
        }
    }
}

The resulting button can be used inside your StoryBoard thanks to the @IBDesignable and @IBInspectable tags.

enter image description here

Also the two properties defined, allow you to set the border width and color directly on interface builder and preview the result.

enter image description here

Other properties could be added in a similar fashion, for border radius and highlight fading time.

Upvotes: 9

Raj Joshi
Raj Joshi

Reputation: 2669

Update with Swift 3

    button.layer.borderWidth = 0.8
    button.layer.borderColor = UIColor.blue.cgColor

enter image description here

Upvotes: 2

Alex
Alex

Reputation: 9720

To change button Radius, Color and Width I set like this:

self.myBtn.layer.cornerRadius = 10;
self.myBtn.layer.borderWidth = 1;
self.myBtn.layer.borderColor =[UIColor colorWithRed:189.0/255.0f green:189.0/255.0f blue:189.0/255.0f alpha:1.0].CGColor;

Upvotes: 8

Vinay Jain
Vinay Jain

Reputation: 1661

You don't need to import QuartzCore.h now. Taking iOS 8 sdk and Xcode 6.1 in referrence.

Directly use:

[[myButton layer] setBorderWidth:2.0f];
[[myButton layer] setBorderColor:[UIColor greenColor].CGColor];

Upvotes: 7

juanjo
juanjo

Reputation: 3757

The problem setting the layer's borderWidth and borderColor is that the when you touch the button the border doesn't animate the highlight effect.

Of course, you can observe the button's events and change the border color accordingly but that feels unnecessary.

Another option is to create a stretchable UIImage and setting it as the button's background image. You can create an Image set in your Images.xcassets like this:

Images.xcassets

Then, you set it as the button's background image:

Button properties

If your image is a template image you can set tint color of the button and the border will change:

Final Button

Now the border will highlight with the rest of the button when touched.

Upvotes: 22

Related Questions