Last active
July 30, 2020 10:16
-
-
Save alfian0/61b00f1057c682a09de4bfd0a460a3a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Author
alfian0
commented
Jul 30, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment