mikeMTOL / UIBarButtonItem-Badge

UIBarButtonItem+Badge
945 stars 167 forks source link

Badge doesn't appear when using multiple items (i.e. rightBarButtonItems) #27

Closed jhickmanEB closed 8 years ago

jhickmanEB commented 8 years ago

When adding multiple UIBarButtonItems to the navigation bar using the rightBarButtonItems property, the badge does not appear. This is a result of the bar button item which should display the badge having the customView property being nil.

Is it possible to apply a fix for this? Would love to use this library to show simple badges, but my app always has multiple UIBarButtonItems in the navigation bar.

jhickmanEB commented 8 years ago

Disregard. For others having the same issue here is the problem/solution:

You must add your UIBarButtonItem(s) to the navigation bar BEFORE setting ANY of the badge properties! As soon as you set a badge property, it tries to initialize the badge. But if you have not added the UIBarButtonItem to the navigationItem(s) stack yet, then there is no superview set yet and the badge doesn't have a view to add to.

😕Bad:

UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-bar-button"]  style:UIBarButtonItemStylePlain target:self action:@selector(barButtonItemPressed:)];
barButtonItem.badgeBGColor = [UIColor redColor];
barButtonItem.badgeValue = @"1";
self.navigationItem.rightBarButtonItems = @[ barButtonItem, someOtherBarButtonItem];

😄Good:

UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-bar-button"]  style:UIBarButtonItemStylePlain target:self action:@selector(barButtonItemPressed:)];
self.navigationItem.rightBarButtonItems = @[ barButtonItem, someOtherBarButtonItem];
barButtonItem.badgeBGColor = [UIColor redColor];
barButtonItem.badgeValue = @"1";