iOS - 在视图控制器之间共享代码
问题描述:
我有两个视图控制器 - 一个UIViewController
和一个UITableViewController
。iOS - 在视图控制器之间共享代码
它们都需要相同的代码barButtonItems
- 完成按钮和设置按钮。我认为这是丑陋的方法选择器和viewDidLoad
相同的代码,但我想不出任何其他方式具有相同的barButtonItems
两个控制器。
共享代码如下所示:
- (void)dismissViewController { [self.navigationController dismissViewControllerAnimated:YES completion:nil]; }
- (void)done:(UIBarButtonItem *)sender { [self dismissViewController]; }
- (void)settings:(UIBarButtonItem *)sender { [self performSegueWithIdentifier:SETTINGS_SEGUE sender:sender]; }
- (void)viewDidLoad {
[super viewDidLoad];
if (self.navigationController.viewControllers.count == 1)
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStyleBordered target:self action:@selector(settings:)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)];
}
架构上,我的代码是这样的:
UITabBarController -view controllers->
UINavigationController -root view controller-> UIViewController
UINavigationController -root view controller-> UITableViewController
那么,有没有共享UIViewController
和UITableViewController
之间的代码的方法吗?谢谢:)
答
如果你真正想要的,你可以在那里你在navigationItem
通过创建一个静态方法initNavigationBar。
+ (void) initNavigationBar: (UiNavigationItem *) navigationItem
{
navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@"Settings" style:UIBarButtonItemStyleBordered
target:selfaction:@selector(settings:)];
navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
}
但是三思而后行。
谢谢!从来没有尝试过在静态方法中使用'target:self',我会尝试。 – s12chung 2013-02-11 22:06:15
o,不是自我,原因是你传递自我,或self.navigationItem作为参数的方法。 – AlexWien 2013-02-11 22:11:14