Установка кнопки в каждом элементе навигации UINavigationController - PullRequest
1 голос
/ 04 мая 2011

Я знаю, что можно добавить пользовательскую кнопку в элемент навигации, используя это:

UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self
               action:@selector(showInfo:)
     forControlEvents:UIControlEventTouchUpInside];

// Add the info button to the navigation bar
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
[self.navigationItem setRightBarButtonItem:barButtonItem
                                  animated:YES];
[barButtonItem release];

Но есть ли способ установки этой кнопки в каждом подпредставлении, помещенном в стек навигации, без необходимости реплицироватьэтот код?

Спасибо!

Ответы [ 2 ]

4 голосов
/ 04 мая 2011

Вы также можете создать подкласс UIViewController, а затем переопределить:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
        [infoButton addTarget:self action:@selector(showInfo:) forControlEvents:UIControlEventTouchUpInside];

        // Add the info button to the navigation bar
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
        [self.navigationItem setRightBarButtonItem:barButtonItem animated:YES];

        [barButtonItem release];
    }
    return self;
}

затем, когда вы создаете новый VC, создайте подкласс этого класса вместо UIViewController

0 голосов
/ 04 мая 2011

При нажатии на «следующий» контроллер вида вы можете добавить этот код:

nextVC.navigationItem.rightBarButtonItem = [self.navigationItem.rightBarButtonItem copy];

Но вы должны перезаписать селектор (если вы хотите, чтобы ваша кнопка отправляла данные вашему объекту nextViewController):

[nextVC.navigationItem.rightBarButtonItem setTarget:nextVC ...];
...