我有一个标签栏控制器作为我的根视图,带有5个导航控制器(每个标签一个)。每个选项卡中的导航栏将具有一个按钮,该按钮在所有选项卡中具有相同的功能。是否有更简单的方法来添加此按钮(并响应选择),而不是将其复制/粘贴到每个导航控制器中?
编辑: 在我的自定义导航控制器的子视图控制器中,我有:
- (void)viewDidLoad
{
[super viewDidLoad];
...
CustomNavigationController *navController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeNavigationController"];
[navController addNotificationsButton:YES searchButton:NO];
}
在自定义导航控制器中我有:
-(void)addNotificationsButton:(BOOL)notifications searchButton:(BOOL)search { //Choose which bar button items to add
NSMutableArray *barItems = [[NSMutableArray alloc]init];
if (notifications) {
//Create button and add to array
UIImage *notificationsImage = [UIImage imageNamed:@"first"];
UIBarButtonItem *notificationsButton = [[UIBarButtonItem alloc]initWithImage:notificationsImage landscapeImagePhone:notificationsImage style:UIBarButtonItemStylePlain target:self action:@selector(notificationsTap:)];
[barItems addObject:notificationsButton];
}
if (search) {
//Create button and add to array
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchTap:)];
[barItems addObject:searchButton];
}
[self.navigationItem setRightBarButtonItems:barItems];
}
但是,当子视图控制器加载时,我只是得到一个空的导航栏。有任何想法吗?
编辑2: 我只需要为视图控制器添加一个参数,我想要添加按钮的导航栏。这是最终的实施......
for CustomViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
...
CustomNavigationController *navController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeNavigationController"];
[navController addNotificationsButton:YES searchButton:NO forViewController:self];
}
对于CustomNavigationController.m
-(void)addNotificationsButton:(BOOL)notifications searchButton:(BOOL)search forViewController:(UIViewController*)vc { //Choose which bar button items to add
NSMutableArray *barItems = [[NSMutableArray alloc]init];
if (notifications) {
//Create button and add to array
UIImage *notificationsImage = [UIImage imageNamed:@"first"];
UIBarButtonItem *notificationsButton = [[UIBarButtonItem alloc]initWithImage:notificationsImage landscapeImagePhone:notificationsImage style:UIBarButtonItemStylePlain target:self action:@selector(notificationsTap:)];
[barItems addObject:notificationsButton];
}
if (search) {
//Create button and add to array
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchTap:)];
[barItems addObject:searchButton];
}
vc.navigationItem.rightBarButtonItems = barItems;
}
答案 0 :(得分:0)
子类导航栏并添加按钮作为子类的一部分。现在,您可以使用子类的5个实例而不是5个基本导航栏,并删除添加按钮的重复工作。
答案 1 :(得分:0)
您需要创建 UINavigationController
的子类,
根据需要配置它(所以使用按钮),
并将其设置为 5导航控制器的类。
显然我无法在这里写下您的所有应用,但重要的是您有办法。
如果您是第一次开发人员,我鼓励您学习关于subclassing
等。