我想出了一个我在整个项目中都在使用的辅助函数。基本上,它会检查栏上是否已经有一个按钮,然后添加新按钮或将其与现有按钮合并。因此,您可以只调用一次或多次该函数:
+ (void)AddButtonToBar:(UIViewController *)controller withImage:(NSString *)imageName withAction:(SEL)action withFrame:(CGRect) frame{
UIButton *newButton =[[UIButton alloc] init];
[newButton setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
newButton.frame = frame;
[newButton addTarget:controller action:action forControlEvents:UIControlEventTouchUpInside];
if ([[controller.navigationItem rightBarButtonItems] count] == 0)
[controller.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:newButton]];
else {
NSMutableArray *existingButtons = [[NSMutableArray alloc] initWithArray:[controller.navigationItem rightBarButtonItems]];
[existingButtons addObject:[[UIBarButtonItem alloc] initWithCustomView:newButton]];
[controller.navigationItem setRightBarButtonItems:(NSArray *)existingButtons];
}
}
从视图控制器调用它:
[Helper AddButtonToBar:self withImage:@"imageName.png" withAction:@selector(myAction) withFrame:CGRectMake(0, 0, 24, 24)];