How to put a badge on customized UIBarButtonItem How to put a badge on customized UIBarButtonItem ios ios

How to put a badge on customized UIBarButtonItem


for Swift 3.0:

Result:

enter image description here

Code:

override func viewDidLoad() {  super.viewDidLoad()  // badge label  let label = UILabel(frame: CGRect(x: 10, y: -10, width: 20, height: 20))  label.layer.borderColor = UIColor.clear.cgColor  label.layer.borderWidth = 2  label.layer.cornerRadius = label.bounds.size.height / 2  label.textAlignment = .center  label.layer.masksToBounds = true  label.font = UIFont(name: "SanFranciscoText-Light", size: 13)  label.textColor = .white  label.backgroundColor = .red  label.text = "80"  // button  let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 16))  rightButton.setBackgroundImage(UIImage(named: "inbox"), for: .normal)  rightButton.addTarget(self, action: #selector(rightButtonTouched), for: .touchUpInside)  rightButton.addSubview(label)  // Bar button item  let rightBarButtomItem = UIBarButtonItem(customView: rightButton)  navigationItem.rightBarButtonItem = rightBarButtomItem}func rightButtonTouched() {  print("right button touched")}


in iOS 8 - I was able to do it by changing the badgeValue

            self.messageButton.badgeValue = @"5";

where message button is a UIBarButton

You have to include these two files to your xcode UIBarButtonItem+Badge.hUIBarButtonItem+Badge.m

which can be found here

Github link to files


You can try this piece of code:-

  UILabel *badgeLbl = [[UILabel alloc]initWithFrame:CGRectMake(16, -2, 18, 18)];badgeLbl.backgroundColor = [UIColor whiteColor];badgeLbl.textColor = [UIColor blackColor];badgeLbl.textAlignment = NSTextAlignmentCenter;badgeLbl.layer.cornerRadius = 9.0;badgeLbl.layer.masksToBounds = true;badgeLbl.text = @"10";UIButton *notificationBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];[notificationBtn setBackgroundImage:[UIImage imageNamed:@"image_name"] forState:UIControlStateNormal];[notificationBtn setTitle:@"" forState:UIControlStateNormal];[notificationBtn addTarget:self action:@selector(onClickAction:) forControlEvents:UIControlEventTouchUpInside];[notificationBtn addSubview:badgeLbl];UIBarButtonItem *notificationBarBtn = [[UIBarButtonItem alloc]initWithCustomView:notificationBtn];self.navigationItem.rightBarButtonItem = notificationBarBtn;