The Simplest iOS Badge

SimplestBadgeLabel
In the past I used a UILabel subclass to show a badge. But since the dawn of flat UI, there’s no need to subclass.

Here is all the code you need:

let label = UILabel()
label.clipsToBounds = true
label.layer.cornerRadius = label.font.pointSize * 1.2 / 2
label.backgroundColor = UIColor.grayColor()
label.textColor = UIColor.whiteColor()
label.text = " Some Text "; // note spaces before and after text

All it does is set the cornerRadius of the label’s underlying CALayer, and add spaces before and after the label text. That’s it!

For nicely organized badge extension for UILabel and UIButton and UIBarButtonItem, see this GitHub gist:
Badge.swift

5 thoughts on “The Simplest iOS Badge

  1. I see your code and the extensions are clear and well written. My compliments. However I am a bit of a novice and having problems using your extension to show a badge on a UIBarButtonItem. Would you mind laying it a specific example for this use case?

  2. let myBarButtonItem = UIBarButtonItem(badge: “42”, title: “How Many Roads”, target: self, action: “answer”)
    // …
    myBarButtonItem.badgeString = “17”

Leave a Reply