使用 splitViewController:willChangeToDisplayMode 时如何显示 barButtonItem:在 iOS8 中

how to show barButtonItem when using splitViewController:willChangeToDisplayMode: in iOS8

我的应用程序结构如下:

UISplitViewController:

the master:NavigationController1->UITableViewController

the detail:NavigationController2->UIWebViewController

我想在视图进入纵向模式时显示 barButtonItem iPad 我知道如何通过 willHideViewController 在 iOS7 中实现它:

-(void)splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)pc{
        barButtonItem.title = @"Course";
        self.navigationItem.leftBarButtonItem = barButtonItem;
}

-(void)splitViewController:(UISplitViewController *)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem{
    if (barButtonItem == self.navigationItem.leftBarButtonItem) {
         self.navigationItem.leftBarButtonItem = nil;
    }
}

但是,此方法在 iOS 8 中已弃用,我尝试使用:

-(void)splitViewController:(UISplitViewController *)svc willChangeToDisplayMode:(UISplitViewControllerDisplayMode)displayMode{
    if (displayMode == UISplitViewControllerDisplayModePrimaryHidden) {
        self.navigationItem.leftBarButtonItem = svc.displayModeButtonItem;
    }else{
        self.navigationItem.leftBarButtonItem = nil;
    }
}

此方法仅在显示模式更改时有效,但在应用首次以纵向启动时无效。 那么如何在第一次以纵向加载应用程序时显示 barButtonItem。

您可以在视图控制器出现时添加栏按钮:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (self.splitViewController.displayMode == UISplitViewControllerDisplayModePrimaryHidden)
    {
        UIBarButtonItem *barButtonItem = self.splitViewController.displayModeButtonItem;
        barButtonItem.title = @"Show master";
        self.navigationItem.leftBarButtonItem = barButtonItem;
    }
}

这只会在母版当前隐藏时添加按钮。

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    if (self.splitViewController.displayMode == UISplitViewControllerDisplayModePrimaryHidden){
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Course" style:self.splitViewController.displayModeButtonItem.style target:self.splitViewController.displayModeButtonItem.target action:self.splitViewController.displayModeButtonItem.action];
    }
}

-(void)splitViewController:(UISplitViewController *)svc willChangeToDisplayMode:(UISplitViewControllerDisplayMode)displayMode{
    if (displayMode == UISplitViewControllerDisplayModePrimaryHidden) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Course" style:svc.displayModeButtonItem.style target:svc.displayModeButtonItem.target action:svc.displayModeButtonItem.action];
    }else{
        self.navigationItem.leftBarButtonItem = nil;
    }
}