Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Badges on UIBarbutton item?

Hi friends am new to iphone developing. Am struggle with add badge values on UIBarbutton item on right side. I have tried but i can't solve this problem. Can anyone help me.

Thanks in advance!

like image 329
Yuvaraj.M Avatar asked Apr 16 '11 05:04

Yuvaraj.M


3 Answers

I know this post is pretty old but with iOS7, MKNumberBadgeView's appearance does not really match the tab bar item badge design. I have found this other component which herits UIBarButtonItem and do the job very well :

https://github.com/TanguyAladenise/BBBadgeBarButtonItem

Hope this may help other iOS7 developers like me

like image 180
phyzalis Avatar answered Nov 07 '22 04:11

phyzalis


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.

like image 34
Yuvaraj.M Avatar answered Nov 07 '22 05:11

Yuvaraj.M


phyzalis has a good answer, there's a categorized version of his solution here:

UIBarButtonItem+Badge

Here's how you can use it:

// Build your regular UIBarButtonItem with Custom View
UIImage *image = [UIImage imageNamed:@"someImage"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0,0,image.size.width, image.size.height);
[button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchDown];
[button setBackgroundImage:image forState:UIControlStateNormal];

// Make BarButton Item
UIBarButtonItem *navLeftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = navLeftButton;

// this is the key entry to change the badgeValue
self.navigationItem.leftBarButtonItem.badgeValue = @"1";
like image 21
Mike Avatar answered Nov 07 '22 03:11

Mike