Skip to content

Instantly share code, notes, and snippets.

@daoseng33
Created June 19, 2019 02:15
Show Gist options
  • Save daoseng33/0cb48665702011aefca155b98bb1a3b1 to your computer and use it in GitHub Desktop.
Save daoseng33/0cb48665702011aefca155b98bb1a3b1 to your computer and use it in GitHub Desktop.
import UIKit
public class BadgeBarButtonItem: UIBarButtonItem {
@IBInspectable
public var badgeNumber: Int = 0 {
didSet {
self.updateBadge()
}
}
@IBInspectable
public var maxCount: Int = 99
@IBInspectable
public var badgeBackgroundColor: UIColor = .red
@IBInspectable
public var badgeTextColor: UIColor = .white
private let label: UILabel
private let badgeSize: CGSize = CGSize(width: 16, height: 16)
private let viewString: String = "view"
required public init?(coder aDecoder: NSCoder) {
let label = UILabel()
label.backgroundColor = badgeBackgroundColor
label.alpha = 0.9
label.layer.cornerRadius = badgeSize.width / 2
label.clipsToBounds = true
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.textColor = badgeTextColor
label.layer.zPosition = 1
label.font = UIFont.systemFont(ofSize: 11)
self.label = label
super.init(coder: aDecoder)
self.addObserver(self, forKeyPath: viewString, options: [], context: nil)
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
self.updateBadge()
}
private func updateBadge() {
guard let view = self.value(forKey: viewString) as? UIView else { return }
self.label.text = badgeNumber > maxCount ? "\(maxCount)+" : "\(badgeNumber)"
if self.badgeNumber > 0 && self.label.superview == nil {
view.addSubview(self.label)
let height = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: badgeSize.height)
let width = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: badgeSize.width)
let centerX = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: -10)
let centerY = NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: -12)
NSLayoutConstraint.activate([height, width, centerX, centerY])
} else if self.badgeNumber == 0 && self.label.superview != nil {
self.label.removeFromSuperview()
}
}
deinit {
self.removeObserver(self, forKeyPath: viewString)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment