Попытка программного создания rightBarButtonItem

Это не работает. Что я делаю не так?

-(void)awakeFromNib{
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showNewEventViewController)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    NSLog(@"awaked");
    [rightBarButtonItem release];
}

Ответы

Ответ 1

Я обычно помещал этот код в метод viewDidLoad, а не в метод awakeFromNib; Я не уверен, что там, где ваша проблема. Что означает "не работает"?

Ответ 2

Я предполагаю, что вы добавили UIBarButtonItem к неправильному объекту! вам нужно добавить его в rootViewController (вместо этого в UINavigationController, как вы, вероятно, сделали)

YourRootViewController *theRootController = [[YourRootViewController alloc] init];

UINavigationController* navContainer = [[UINavigationController alloc] initWithRootViewController:theRootController];

UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(dismiss)];    
theRootController.navigationItem.rightBarButtonItem = btnCancel

[navContainer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentModalViewController:navContainer animated:YES];

Ответ 3

Попробуйте это вместо:

- (void) initUI {   
   UIBarButtonItem *btnCancel = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" 
                                  style:UIBarButtonItemStyleBordered 
                                  target:self 
                                  action:@selector(dismiss)]autorelease];    

   self.navigationItem.rightBarButtonItem = btnCancel;

   //[btnCancel release]; no need to explicitly release the item

}