Skip to content

Instantly share code, notes, and snippets.

@alexpls
Last active August 7, 2016 09:59
Show Gist options
  • Save alexpls/95279b3f9a2da7f2d7bf to your computer and use it in GitHub Desktop.
Save alexpls/95279b3f9a2da7f2d7bf to your computer and use it in GitHub Desktop.
UIButton subclass where borderRadius can be set for each corner individually
//
// BorderedButton.swift
//
// A UIButton subclass where you can choose which corners (top left, top right,
// bottom left, bottom right) of the button you want to have a borderRadius on.
// Either set these in code or in Interface Builder.
//
import UIKit
@IBDesignable
class BorderedButton: UIButton {
@IBInspectable var borderColor: UIColor = UIColor(red:0.020, green:0.522, blue:1, alpha:1)
@IBInspectable var borderWidth: CGFloat = 1
@IBInspectable var cornerRadius: CGFloat = 4
@IBInspectable var roundCornerTopLeft: Bool = true
@IBInspectable var roundCornerTopRight: Bool = true
@IBInspectable var roundCornerBottomLeft: Bool = true
@IBInspectable var roundCornerBottomRight: Bool = true
private var borderLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func setupView() {
borderLayer.strokeColor = borderColor.CGColor
borderLayer.borderWidth = borderWidth
borderLayer.fillColor = UIColor.whiteColor().colorWithAlphaComponent(0).CGColor
layer.insertSublayer(borderLayer, atIndex: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
var rectCorners: UIRectCorner = []
if roundCornerTopLeft { rectCorners.insert(.TopLeft) }
if roundCornerTopRight { rectCorners.insert(.TopRight) }
if roundCornerBottomLeft { rectCorners.insert(.BottomLeft) }
if roundCornerBottomRight { rectCorners.insert(.BottomRight) }
let borderPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: rectCorners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
borderLayer.path = borderPath.CGPath
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment