Skip to content

Instantly share code, notes, and snippets.

@davidlawson
Last active December 8, 2021 10:33
Show Gist options
  • Save davidlawson/e9140d1e5cd533ff503c15111c1908df to your computer and use it in GitHub Desktop.
Save davidlawson/e9140d1e5cd533ff503c15111c1908df to your computer and use it in GitHub Desktop.
UIBarButtonItem with badge, Swift 4, iOS 9/10/11
import UIKit
public class BadgeBarButtonItem: UIBarButtonItem
{
@IBInspectable
public var badgeNumber: Int = 0 {
didSet {
self.updateBadge()
}
}
private let label: UILabel
required public init?(coder aDecoder: NSCoder)
{
let label = UILabel()
label.backgroundColor = .red
label.alpha = 0.9
label.layer.cornerRadius = 9
label.clipsToBounds = true
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.textColor = .white
label.layer.zPosition = 1
self.label = label
super.init(coder: aDecoder)
self.addObserver(self, forKeyPath: "view", 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: "view") as? UIView else { return }
self.label.text = "\(badgeNumber)"
if self.badgeNumber > 0 && self.label.superview == nil
{
view.addSubview(self.label)
self.label.widthAnchor.constraint(equalToConstant: 18).isActive = true
self.label.heightAnchor.constraint(equalToConstant: 18).isActive = true
self.label.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 9).isActive = true
self.label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -9).isActive = true
}
else if self.badgeNumber == 0 && self.label.superview != nil
{
self.label.removeFromSuperview()
}
}
deinit {
self.removeObserver(self, forKeyPath: "view")
}
}
@dan085
Copy link

dan085 commented Oct 9, 2021

not work!

@dan085
Copy link

dan085 commented Oct 9, 2021

not show bubble

@mudassir-abbas-brainx
Copy link

i know why bubble is not showing reason

guard let view = self.value(forKey: "view") as? UIView else { return }

this statement is only called with else condition

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