I am adding a badge to a UIBarButtonItem… which works fine. But I cannot remove it. Any help is appreciated.
Thanks.
Code:
MKNumberBadgeView *badge = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(45, -10, 30,30)];
badge.value = @"!";
badge.layer.cornerRadius = 10;
badge.layer.masksToBounds = YES;
badge.tag = 42;
if ([self.chatCount isEqualToString:@"1"]) {
[chatButton addSubview:badge];
} else {
for (UIView *view in [self.view subviews] ) { if (view.tag == 42 ) { [view removeFromSuperview]; } }
[badge release];
}
UIBarButtonItem *chat = [[UIBarButtonItem alloc] initWithCustomView:chatButton];
self.navigationItem.rightBarButtonItem = chat;
[chat release];
You’re adding your badge as a subview to chatButton not self.view. Your for loop is iterating over self.view.subviews and badge is not a subview of self.view but a subview of chatbutton. You will either have to iterate over chatButton.subviews or create a recursive method that iterates over all subviews. Alternatively, you can use viewWithTag which I think searches the entire hierarchy.
I would just hold an instance variable to badge and call [self.badge removeFromSuperview] or self.badge.hidden = YES;