iOS - 在视图控制器之间共享代码

时间:2013-02-11 21:50:00

标签: iphone refactoring uitabbarcontroller viewcontroller

我有两个视图控制器 - UIViewControllerUITableViewController

他们都需要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

那么,有没有办法在UIViewControllerUITableViewController之间共享代码?谢谢:))

1 个答案:

答案 0 :(得分:0)

如果您真的想要,可以在初始导航栏中创建一个静态方法,在其中传入navigationItem

+ (void ) initNavigationBar: (UiNavigationItem *) navigationItem 
{
      navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
         initWithTitle:@"Settings" style:UIBarButtonItemStyleBordered 
         target:selfaction:@selector(settings:)];

      navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] 

}

但如果有意义,请三思而后行。