Правая кнопка не отображается в пользовательском контроллере навигации

#ios #objective-c #uinavigationcontroller

#iOS #objective-c #uinavigationcontroller

Вопрос:

Мое приложение представляет собой приложение с панелью вкладок со многими контроллерами навигации. Я хочу, чтобы эти навигационные контроллеры обрабатывали действия входа / выхода с помощью пользовательской кнопки правой панели. Итак, я настроил свою панель вкладок в AppDelegate таким образом :

 MyFirstViewController *firstViewController = [[MyFirstViewController alloc] init];
UIViewController *firstNavigationController = [[CustomNavigationController alloc]
                                               initWithRootViewController:firstViewController];

MySecondViewController *secondViewController = [[MySecondViewController alloc] init];
UIViewController *secondNavigationController = [[CustomNavigationController alloc]
                                               secondViewController]
                                               initWithRootViewController:secondViewController];

....

[tabBarController setViewControllers:@[firstNavigationController, secondNavigationController]];
  

Затем CustomNavigationController :

 @implementation ConnectionNavigationController

- (void) viewDidLoad 
{
    [self displayConnectionButton];
}

- (void) displayConnectionButton
{
    UIImage *portraitImage, *landscapeImage;
    portraitImage = [UIImage imageNamed:@"conn.png"];
    landscapeImage = [UIImage imageNamed:@"connLandscape.png"];

    UIBarButtonItem *connButton = [[UIBarButtonItem alloc]
                                   initWithImage:[portraitImage
                                                  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                   landscapeImagePhone:[landscapeImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                   style:UIBarButtonItemStylePlain target:self action:@selector(showConnectionPopup)];
    self.navigationItem.rightBarButtonItem = connButton;
}

@end
  

Я пытался с viewDidLoad помощью , viewDidAppear , viewWillAppear но ничего не работает, я не могу заставить эту кнопку отображаться на панели навигации. Я также пытался добавить reloadInputViews или setNeedsDisplay . Что мне делать?

Спасибо за вашу помощь

Редактировать: интерфейс CustomNavigationController

 @interface ConnectionNavigationController : UINavigationController

- (void) displayConnectionButton;

@end
  

Комментарии:

1. Не могли бы вы добавить @interface of ConnectionNavigationController , пожалуйста?

2. @lucianomarisi Я это сделал, вы увидите, что в этом не так много.

Ответ №1:

Насколько я понимаю, вы должны добавить displayConnectionButton метод в соответствующий UIViewController подкласс, а не в свой UINavigationController подкласс, поскольку он содержит только стек контроллеров представления.

Например.

 @implementation MyFirstViewController

- (void) viewDidLoad 
{
    [self displayConnectionButton];
}

- (void) displayConnectionButton
{
    UIImage *portraitImage, *landscapeImage;
    portraitImage = [UIImage imageNamed:@"conn.png"];
    landscapeImage = [UIImage imageNamed:@"connLandscape.png"];

    UIBarButtonItem *connButton = [[UIBarButtonItem alloc]
                                   initWithImage:[portraitImage
                                                  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                   landscapeImagePhone:[landscapeImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                   style:UIBarButtonItemStylePlain target:self action:@selector(showConnectionPopup)];
    self.navigationItem.rightBarButtonItem = connButton;
}

@end
  

В качестве примечания, если вы поставите точку останова displayConnectionButton в своем CustomNavigationController , и po self.viewControllers я думаю, вы получите пустой массив (т. Е. Без контроллеров просмотра)

Комментарии:

1. Спасибо за ваш ответ. Это то, что я сделал первым, но если я это сделаю, мне придется добавлять один и тот же код в каждый контроллер моего приложения, верно?

2. У вас может быть BaseViewController класс с этим кодом и подкласс вашего MyFirstViewController и MySecondViewController из него.

3. Это правильно. UINavigationBar (внутри вашего UINavigationController) управляет стеком UINavigationItems, который он получает от всех ваших UIViewControllers. Для получения дополнительной информации прочитайте документ UIViewController для navigationItem.