18

I have a navigation bar with two buttons, one is a back button the other a chat symbol.

I write this code like this:

UIBarButtonItem *_btn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"]
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(goBackToPreviousView)];

self.navigationItem.leftBarButtonItem=_btn;
self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];


UIBarButtonItem *_btn2=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"chat.png"]
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(startChat)];

self.navigationItem.rightBarButtonItem=_btn2;
self.navigationItem.rightBarButtonItem.tintColor = [Utility colorWithHexValue:CyanBlue];

The problem I have is that whenever there is some new messages in the chat that I have not seen, there should be like a badge of some sort, or a customized label over the chat button, to indicate how many new messages you have.

How do I do this?

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
niper007
  • 191
  • 1
  • 1
  • 5
  • Show the efforts you've made in implementing one. – Mick MacCallum Jun 12 '14 at 09:30
  • How about writing some code to check if you have some unread messages or not in your `viewDidLoad` method. And if returns true, then change the image of the button, else keep it as it is. – Dhrumil Jun 12 '14 at 09:31
  • I have code that gives me the number of chat message I have not seen. The problem is that the image has to have that number in it. So that would mean I had to insert alot of images. – niper007 Jun 12 '14 at 09:37
  • I tried to write out the number on the button with : self.navigationItem.rightBarButtonItem.title = @"2"; but doesn't seem to work. – niper007 Jun 12 '14 at 09:38
  • hey @niper007, How to resolve this issue. – Chirag Kothiya Aug 23 '18 at 13:31

7 Answers7

37

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")
}
Community
  • 1
  • 1
Wilson
  • 9,006
  • 3
  • 42
  • 46
  • 1
    After doing this, the tint color for my bar button images was not being respected. I needed to set the tint color on the image itself, and set the rendering mode on my image to Always Template – stepheaw Sep 15 '19 at 02:13
11

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.h UIBarButtonItem+Badge.m

which can be found here

Github link to files

Doug Amos
  • 4,243
  • 1
  • 22
  • 23
TheRealRonDez
  • 2,807
  • 2
  • 30
  • 40
  • UIBarButtonItem+Badge.h UIBarButtonItem+Badge.m – TheRealRonDez Sep 09 '15 at 09:59
  • Above link provides a great category to do this. Gave me exactly what I needed. – Carl Hine Oct 05 '16 at 12:03
  • Would also like to add that this category could be ineffective if used in the viewDidLoad method. The - (void)viewDidAppear:(BOOL)animated {} method is where your configuration and setup badge cals ought to go. Suspect the UIBarButtons are not quite there until viewDidAppear – Carl Hine May 17 '18 at 09:47
6

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;
  • This is the one I prefer (+1). It works on iOS11.4. It has one problem which is easily fixed. The icon image should be initialised as [[UIImage imageNamed:@"image_name"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] so that the icon inherits the same, or default, UI color tint as any other icons displayed. – Seoras Jul 09 '18 at 22:44
3

Good day! Here is my version - easy and without any problems:

navBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 64)];
[self.view addSubview:navBar];

navItem    = [[UINavigationItem alloc] initWithTitle:NSLocalizedString(@"Meetings", nil)];

[navBar pushNavigationItem:navItem animated:NO];
    UIButton *chat = [UIButton buttonWithType: UIButtonTypeRoundedRect];
[chat setTitle:@"Chat" forState: UIControlStateNormal];
    UILabel *badge  = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 20, 20)];
badge.textColor = [UIColor darkGrayColor];
badge.font      = [UIFont fontWithName: fontName size: 15];
badge.text      = @"10";
badge.textAlignment = NSTextAlignmentCenter;

badge.layer.cornerRadius = 10.0f;
badge.layer.backgroundColor = [UIColor yellowColor].CGColor;
badge.clipsToBounds      = YES;

badge.center = CGPointMake(50, 20);

[chat addSubview: badge];

navItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: chat];

have a nice day!

Pavel
  • 167
  • 2
  • 11
2

try custom methods

  1. https://github.com/TanguyAladenise/BBBadgeBarButtonItem

  2. http://yuvarajmanickam.wordpress.com/2012/02/01/add-badges-on-uibarbuttonitem-in-iphone-app/

  3. How to add Badges on UIBarbutton item?

  4. https://www.cocoacontrols.com/controls/mknumberbadgeview

Community
  • 1
  • 1
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
1

You can try this category

UIBarButtonItem-Badge

jos
  • 1,070
  • 12
  • 22
0

Try this customized control - mknumberbadgeview

Muruganandham K
  • 5,271
  • 5
  • 34
  • 62