从UIBarButtonItem中删除徽章子视图

时间:2012-02-03 02:27:43

标签: iphone uibarbuttonitem badge

我正在为UIBarButtonItem添加徽章......工作正常。但我不能删除它。任何帮助表示赞赏。

感谢。

代码:

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];

1 个答案:

答案 0 :(得分:3)

您将徽章作为子视图添加到chatButton而不是self.view。你的for循环遍历self.view.subviews并且badge不是self.view的子视图,而是chatbutton的子视图。您将不得不迭代chatButton.subviews或创建迭代所有子视图的递归方法。或者,您可以使用我认为搜索整个层次结构的viewWithTag

我只是将一个实例变量保存到徽章并调用[self.badge removeFromSuperview]或self.badge.hidden = YES;