Skip to content

Instantly share code, notes, and snippets.

@alfian0
Last active July 30, 2020 10:16
Show Gist options
  • Save alfian0/61b00f1057c682a09de4bfd0a460a3a0 to your computer and use it in GitHub Desktop.
Save alfian0/61b00f1057c682a09de4bfd0a460a3a0 to your computer and use it in GitHub Desktop.
@IBDesignable class Badge: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
@IBInspectable var round: CGFloat = 7.0 {
didSet {
layer.cornerRadius = round
clipsToBounds = true
}
}
@IBInspectable
var type: Int = 0 {
didSet {
_type = BadgeType(rawValue: type) ?? .primary
}
}
var _type: BadgeType = .primary {
didSet {
setup()
}
}
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
func setup() {
layer.cornerRadius = round
clipsToBounds = true
textColor = _type.textColor
backgroundColor = _type.backgroundColor
font = UIFont.systemFont(ofSize: 12, weight: .bold)
}
}
enum BadgeType: Int {
case primary
case secondary
case success
case danger
case warning
case info
var backgroundColor: UIColor {
switch self {
case .primary:
return .systemBlue
case .secondary:
return .lightGray
case .success:
return .systemGreen
case .danger:
return .systemRed
case .warning:
return .systemYellow
case .info:
return .systemTeal
}
}
var textColor: UIColor {
switch self {
case .warning:
return .darkGray
default:
return .white
}
}
}
@alfian0
Copy link
Author

alfian0 commented Jul 30, 2020

Screen Shot 2020-07-30 at 17 15 00

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