How to Add Badges on Uibarbutton Item

how to put badge on UIBarButtonItem in swift 4?

Here it is a simple solution for putting the badge on a navigation bar

let filterBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
filterBtn.setImage(UIImage.fontAwesomeIcon(name: .filter, style: .solid,
textColor: UIColor.white,
size: CGSize(width: 25, height: 25)), for: .normal)
filterBtn.addTarget(self, action: #selector(filterTapped), for: .touchUpInside)

let lblBadge = UILabel.init(frame: CGRect.init(x: 20, y: 0, width: 15, height: 15))
self.lblBadge.backgroundColor = COLOR_GREEN
self.lblBadge.clipsToBounds = true
self.lblBadge.layer.cornerRadius = 7
self.lblBadge.textColor = UIColor.white
self.lblBadge.font = FontLatoRegular(s: 10)
self.lblBadge.textAlignment = .center

filterBtn.addSubview(self.lblBadge)

self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(customView: filterBtn)]

In your case

self.navigationItem.rightBarButtonItems = [notificationLabel.init(customView: filterBtn)]

Add badge alert in right bar button item in swift

Create File named 'UIBarButtonItem+Badge.swift'
and add the following code

import UIKit

extension CAShapeLayer {
func drawRoundedRect(rect: CGRect, andColor color: UIColor, filled: Bool) {
fillColor = filled ? color.cgColor : UIColor.white.cgColor
strokeColor = color.cgColor
path = UIBezierPath(roundedRect: rect, cornerRadius: 7).cgPath
}
}

private var handle: UInt8 = 0;

extension UIBarButtonItem {
private var badgeLayer: CAShapeLayer? {
if let b: AnyObject = objc_getAssociatedObject(self, &handle) as AnyObject? {
return b as? CAShapeLayer
} else {
return nil
}
}

func setBadge(text: String?, withOffsetFromTopRight offset: CGPoint = CGPoint.zero, andColor color:UIColor = UIColor.red, andFilled filled: Bool = true, andFontSize fontSize: CGFloat = 11)
{
badgeLayer?.removeFromSuperlayer()

if (text == nil || text == "") {
return
}

addBadge(text: text!, withOffset: offset, andColor: color, andFilled: filled)
}

private func addBadge(text: String, withOffset offset: CGPoint = CGPoint.zero, andColor color: UIColor = UIColor.red, andFilled filled: Bool = true, andFontSize fontSize: CGFloat = 11)
{
guard let view = self.value(forKey: "view") as? UIView else { return }

var font = UIFont.systemFont(ofSize: fontSize)

if #available(iOS 9.0, *) { font = UIFont.monospacedDigitSystemFont(ofSize: fontSize, weight: UIFont.Weight.regular) }
let badgeSize = text.size(withAttributes: [NSAttributedStringKey.font: font])

// Initialize Badge
let badge = CAShapeLayer()

let height = badgeSize.height;
var width = badgeSize.width + 2 /* padding */

//make sure we have at least a circle
if (width < height) {
width = height
}

//x position is offset from right-hand side
let x = view.frame.width - width + offset.x

let badgeFrame = CGRect(origin: CGPoint(x: x, y: offset.y), size: CGSize(width: width, height: height))

badge.drawRoundedRect(rect: badgeFrame, andColor: color, filled: filled)
view.layer.addSublayer(badge)

// Initialiaze Badge's label
let label = CATextLayer()
label.string = text
label.alignmentMode = kCAAlignmentCenter
label.font = font
label.fontSize = font.pointSize

label.frame = badgeFrame
label.foregroundColor = filled ? UIColor.white.cgColor : color.cgColor
label.backgroundColor = UIColor.clear.cgColor
label.contentsScale = UIScreen.main.scale
badge.addSublayer(label)

// Save Badge as UIBarButtonItem property
objc_setAssociatedObject(self, &handle, badge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}

private func removeBadge() {
badgeLayer?.removeFromSuperlayer()
}
}

And now simple add the badge in UIBarButtonItem like this:

let rightBarButton = self.navigationItem.rightBarButtonItem

rightBarButton?.addBadge(number: 4)

How to add badge for bar button?

Download class from here UIBarButtonItem-Badge and import in your project only UIBarButtonItem+Badge.h or UIBarButtonItem+Badge.m class in project
and import in your class

#import "UIBarButtonItem+Badge.h"

write down only one line for set badge

self.navigationItem.rightBarButtonItem.badgeValue = @"5"; //your value 

Swift 3

for me, it was not working without DispatchQueue

        DispatchQueue.main.async {
self.navigationItem.rightBarButtonItem.badgeBGColor = UIColor.red
self.navigationItem.rightBarButtonItem.badgeValue = "\(5)"
}

How to add Badges on UIBarbutton item?

Finally i found the way to add badges on UIBarbutton item. I searched lot but not found the correct answer. So i created UIButton and add it as a Custom view on rightbarbutton item. Add add the MKNumberBadgeView for display the badge number. Below i have add my code for you.

// Initialize NKNumberBadgeView...
MKNumberBadgeView *number = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(60, 00, 30,20)];
number.value = 10;

// Allocate UIButton
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 70, 30);
btn.layer.cornerRadius = 8;
[btn setTitle:@"Button" forState:UIControlStateNormal];
[btn addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
//[btn setBackgroundColor:[UIColor blueColor]];
[btn setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.1 alpha:0.2]];
btn.font = [UIFont systemFontOfSize:13];
//[btn setFont:[UIFont systemFontOfSize:13]];
[btn addSubview:number]; //Add NKNumberBadgeView as a subview on UIButton

// Initialize UIBarbuttonitem...
UIBarButtonItem *proe = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = proe;

Thanks.



Related Topics



Leave a reply



Submit