How to Add a badge to UIButton

9.7k views Asked by At

In my app I need to add count at left top to UIButton like UIButtonItem. How it is possible and how to add MIBadgeButton to my project.

3

There are 3 answers

3
Yogesh Mv On

For adding a badge count to UIBUtton you need to add the custom view as a subview to UIButton, there is no direct way. For adding MIBadgeButton to the project: 2 Ways:

  1. Add through a CocoaPods as mentioned in the link https://github.com/mustafaibrahim989/MIBadgeButton

  2. Add as Submodule -> Download project from Github. Copy the MIBadgeButton and MIBadgeLabel files then add them to your project. Refer to their example project for a clear understanding

1
carlson On

I solved it by defining a subclass of UIButton, including a function to add and another to remove the badge.

class ButtonWithBadge: UIButton {

required init() {
        super.init(frame: .zero)
    }

required init?(coder: NSCoder) {
    super.init(coder: coder)
}

func addBadge(withBadgeTag tag: Int, badgeSize size: CGSize = CGSize(width: 7, height: 7), indentTop: CGFloat = 3, indentRight: CGFloat = 3) {
    let badge: UILabel = {
        let bdg = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        bdg.tag = tag
        bdg.translatesAutoresizingMaskIntoConstraints = false
        bdg.layer.cornerRadius = bdg.bounds.size.height / 2
        bdg.layer.masksToBounds = true
        bdg.backgroundColor = .systemRed
        return bdg
    }()
    self.addSubview(badge)
    NSLayoutConstraint.activate([
        badge.rightAnchor.constraint(equalTo: self.rightAnchor, constant:  -indentRight),
        badge.topAnchor.constraint(equalTo: self.topAnchor, constant: indentTop),
        badge.widthAnchor.constraint(equalToConstant: size.width),
        badge.heightAnchor.constraint(equalToConstant: size.height)
        ])
}

func removeBadge(withBadgeTag tag: Int) {
    if let badge = self.viewWithTag(tag) {
            badge.removeFromSuperview()
        }
}

}

The optional parameters of the function "addBadge" allow to define the size of the badge and the position relative to the topAnchor and rightAnchor of the button in cases where the defaults are not appropriate.

For use, either add a button in the Storyboard and link it to the class ButtonWithBadge and switch the badge on or off as required:

class ViewController: UIViewController {

@IBOutlet weak var myButton: ButtonWithBadge!

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(myButton)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    // if condition for showing badge with defaults ( size = 7, indents = 3):
    myButton.addBadge(withBadgeTag: 12345)
    
    // or alternatively create badge with size 10 and indents of 5
    myButton.addBadge(withBadgeTag: 12345, badgeSize: CGSize(width: 10, height: 10), indentTop: 5, indentRight: 5)
    
    // if condition is equal to no badge:
    myButton.removeBadge(withBadgeTag: 12345)
}

}

If you want to show a content (e.g. number) in the badge, just adjust the size and add the input as additional parameter in the function 'addBadge' and assign it to the label

0
Gerges Eid On

You could use this pod

First clone the repo in your xcode Then import the library in your file

  1. add podfile to your project

  2. add this line 'pod BadgeControl' to your podfile

your podfile will be like that

platform :ios, '9.0'
target 'myProject' do
use_frameworks!
# Pods for myProject
pod 'BadgeControl'
end

Then close your Xcode project Then pod install in your terminal

Then open myProject.xcworkspace instead of myProject.xcodeproj

Open storyboard add button , connect it to your viewcontroller file and give it a name then import BadgeControl

import BadgeControl
class ViewController: UIViewController {

@IBOutlet weak var badgeButton: UIButton!

private var upperLeftBadge: BadgeController!

override func viewDidLoad() {
    super.viewDidLoad()

    // Add badge to button
    upperLeftBadge = BadgeController(for: badgeButton, in: .upperLeftCorner, badgeBackgroundColor: #colorLiteral(red: 0.9674351811, green: 0.2441418469, blue: 0.4023343325, alpha: 1) , badgeHeight: 20, badgeTextColor: UIColor.white, borderWidth: 3)

    upperLeftBadge.addOrReplaceCurrent(with: "123 or abc", animated: true)

    upperLeftBadge.animateOnlyWhenBadgeIsNotYetPresent = true
    upperLeftBadge.animation = BadgeAnimations.leftRight
}
}

You could change position of the badge 'upperLeftCorner' with lowerLeftCorner, upperRightCorner and lowerRightCorner

And you could change the animation 'leftRight' with rightLeft, fadeIn and rolling

And you could change badgeBackgroundColor and badgeTextColor to any color you want

Also you could change badgeHeight

Change this line

upperLeftBadge.animateOnlyWhenBadgeIsNotYetPresent = false

if you want animation when badge is already present on the view.

Run your project.