Skip to content

Instantly share code, notes, and snippets.

@Isuru-Nanayakkara
Last active August 9, 2021 12:11
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save Isuru-Nanayakkara/496d5713e61125bddcf5 to your computer and use it in GitHub Desktop.
Save Isuru-Nanayakkara/496d5713e61125bddcf5 to your computer and use it in GitHub Desktop.
Add a border to a UIButton. Original code - http://stackoverflow.com/a/21881788/1077789
import Foundation
import UIKit
public enum UIButtonBorderSide {
case Top, Bottom, Left, Right
}
extension UIButton {
public func addBorder(side: UIButtonBorderSide, color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
switch side {
case .Top:
border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: width)
case .Bottom:
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
case .Left:
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
case .Right:
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
}
self.layer.addSublayer(border)
}
}
@dinhnhat0401
Copy link

@capJavert
Copy link

Swift 4 + we can add this extension to UIView so its available across more elements.

public enum UIButtonBorderSide {
    case top, bottom, left, right
}

extension UIView {
    
    public func addBorder(side: UIButtonBorderSide, color: UIColor, width: CGFloat) {
        let border = CALayer()
        border.backgroundColor = color.cgColor
        
        switch side {
        case .top:
            border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: width)
        case .bottom:
            border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
        case .left:
            border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
        case .right:
            border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
        }
        
        self.layer.addSublayer(border)
    }
}

@eddievarg
Copy link

lmL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment