在navigationController中有一个通用栏按钮项

时间:2014-02-28 13:43:14

标签: ios uinavigationcontroller uinavigationbar uibarbuttonitem uinavigationitem

我的应用中有UINavigationController,我希望在我的应用中显示的所有导航栏中显示正确的UIBarButtonItem。这个按钮会加载菜单,所以我不想手动在每个导航栏中添加这个按钮,因为该功能正在加载菜单,我不想复制/过去这个按钮的动作。

有没有办法在ViewController.h.m中处理此问题?

所以按钮充当通用栏按钮项目?

6 个答案:

答案 0 :(得分:12)

您可以做的是将导航控制器子类化。这是一个例子

@interface NavigationController : UINavigationController
@end

@interface NavigationController () <UINavigationBarDelegate>
@end

@implementation NavigationController

- (void)viewDidLoad
{
    [super viewDidLoad];
    for (UIViewController* viewController in self.viewControllers){
        // You need to do this because the push is not called if you created this controller as part of the storyboard
        [self addButton:viewController.navigationItem];         
    }
}

-(void) pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [self addButton:viewController.navigationItem];
    [super pushViewController:viewController animated:animated];
}

-(void) addButton:(UINavigationItem *)item{
    if (item.rightBarButtonItem == nil){
        item.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(action:)];
    }
}

-(void) action:(UIBarButtonItem*) button{

}

@end

答案 1 :(得分:1)

除非您使用自定义视图看起来像NavigationBar,否则无法执行此操作。 默认情况下,当推送或弹出ViewController时,NavigationController会清除所有栏按钮项。因此,对于每个ViewController,您需要每次在函数

中创建UIBarButtonItem
- (void)viewWillAppear:(BOOL)animated

或者使用can子类UINavigationController并按@ rp90回答。

答案 2 :(得分:1)

您可以通过在UINavigationController的委托中添加一个出现在UINavigationController中的按钮来添加它 - 在本例中,是一个单例助手类。

斯威夫特3:

class NavHelper: UINavigationControllerDelegate {
    static let shared = NavHelper()

    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        let barButtonItem = UIBarButtonItem(image: <yourButtonImage>, style: .plain, target: NavHelper.shared, action: #selector(NavDelegate.handleButton(_:)))
        viewController.navigationItem.rightBarButtonItem = barButtonItem
    }

    func handleButton(_ sender: UIBarButtomItem) {
        <yourCode>
    }
}

答案 3 :(得分:0)

另一种选择是将您自己的导航栏视图作为UIViewController的一部分。您可以关闭Apple并构建自己的Apple。我们这样做是为了让我们自己的控件更容易。你唯一丢失的是iOS 7下的简单半透明效果。许多应用程序都是这样做的,原因和我们一样。

答案 4 :(得分:0)

您可以创建一个继承自UIViewController的新类,并在viewDidLoad方法中创建UIBarButtonItem并将其作为左/右栏添加到navigationItem项目。假设这个类名为CustomBarViewController

UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:@"hi" style:UIBarButtonItemStylePlain target:self action:@selector(doSomething:)];
[self.navigationItem setRightBarButtonItem:barItem];

在现有的视图控制器中,您可以让他们使用UIViewController代替.h,而不是让它们从CustomBarViewController文件中继承。

@interface MyExistingViewController : CustomBarViewController

然后,您可以将操作放入doSomething:方法,或者将通知传递给现有的视图控制器。

答案 5 :(得分:0)

您可以将按钮添加到ContainerView中。因此它将始终开启。 值得深思的话......