How can I add a badge to a standard UIButton?

IphoneCocoa TouchIosBadge

Iphone Problem Overview


Is it possible to add a standard-looking badge to a standard UIButton?

If it's not supported semi-natively, what would be the simplest way to achieve this?

Example image:

An iPhone UI button

Iphone Solutions


Solution 1 - Iphone

Here's a VERY NICE class by Sascha Paulus called CustomBadge, that builds and renders custom badges using Core Graphics. They're just UIView subclasses, so you lay them out using their frame just like any other UIView subclass.

I've used this library many times and always been pleased with the results. Flexible, easy to use. Totally recommend it.

Solution 2 - Iphone

You can check for several options here: CocoaControls Badges

Solution 3 - Iphone

The class that Apple uses is _UIBadgeView (https://github.com/nst/iOS-Runtime-Headers/blob/master/Frameworks/UIKit.framework/_UIBadgeView.h), but of course, this class is private (note the underscore) and not documented.

Here's another class that implements this view with the same look and feel as Apple's while also allowing you to customize it: https://github.com/JaviSoto/JSBadgeView. The great thing about this one is that it lets you position the badge relative to another view automatically, in one of its corners.

Solution 4 - Iphone

We have a badge view in Nimbus that's super easy to use and well documented:

NimbusBadge

Solution 5 - Iphone

I don't know how this is done out of the box and I honestly doubt that Apple built that into the SDK.

Anyway, you could create a custom view with a button on it, add the background of the badge as a UIImageView and place a label on it to hold the badge count.

That's a quick solution, it might be better to create a custom subclass of UIButton and add your badge stuff as a subview

Solution 6 - Iphone

I'd go a similar way as @Björn Kaiser: Use the button as you like it, and then add a custom view with that badge as a subview to it - I've done it and it works well.

As for the view, you can draw it as you like. You can draw it manually or use CoreAnimation and let it make the main part, i.e. theBadge.layer.cornerRadius = ...; to give it a round shape, draw the text/number in drawRect: or add it as a label etc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionohadprView Question on Stackoverflow
Solution 1 - IphoneDan RayView Answer on Stackoverflow
Solution 2 - IphoneCarlos RicardoView Answer on Stackoverflow
Solution 3 - IphoneJavier SotoView Answer on Stackoverflow
Solution 4 - IphonefeatherlessView Answer on Stackoverflow
Solution 5 - IphoneBjörn KaiserView Answer on Stackoverflow
Solution 6 - IphoneEikoView Answer on Stackoverflow