How can I add a badge to a standard UIButton? [clo

2020-01-27 00:40发布

问题:

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 5 years ago.

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:

回答1:

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.



回答2:

You can check for several options here: CocoaControls Badges



回答3:

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.



回答4:

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

NimbusBadge



回答5:

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



回答6:

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.