In this article, I am going to show you how to add badge on button using custom label in Swift.
Implement Button
let’s get start by adding button in a storyboard. In this case, I will implement cart button using UIButton
to the navigation bar.
Let’s implement code as below and connect the code to UIButton.
@IBOutlet var cartButton: UIButton!
Creating the badge
I will use label to create the badge and setup background color, text font and text color for the badge that call badgeLabel
.
lazy var badgeLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
label.translatesAutoresizingMaskIntoConstraints = false
label.layer.cornerRadius = label.bounds.size.height / 2
label.textAlignment = .center
label.layer.masksToBounds = true
label.textColor = .white
label.font = label.font.withSize(12)
label.backgroundColor = .systemRed
return label
}()
Setup the badge
Let’s add the badge to the button and set layout constraints for the badge.
func showBadge(count: Int) {
badgeLabel.text = "\(count)"
cartButton.addSubview(badgeLabel) let constraints = [
badgeLabel.leftAnchor.constraint(equalTo: cartButton.centerXAnchor, constant: 2),
badgeLabel.topAnchor.constraint(equalTo: cartButton.topAnchor, constant: -6),
badgeLabel.widthAnchor.constraint(equalToConstant: 16),
badgeLabel.heightAnchor.constraint(equalToConstant: 16)
] NSLayoutConstraint.activate(constraints)
}
You can also customize width and height of the badge as the code above.
Show the badge
The badge is ready now, then let’s show it by implement it in viewDidLoad
.
showBadge(count: 5)