尝试以编程方式创建rightBarButtonItem

时间:2010-01-19 01:00:44

标签: iphone uibarbuttonitem

这似乎不起作用。我究竟做错了什么?

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

3 个答案:

答案 0 :(得分:22)

我的猜测是,你将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];

答案 1 :(得分:11)

我通常会将此代码放在viewDidLoad方法而不是awakeFromNib方法中;我不确定这是你的问题所在。 “不工作”是什么意思?

答案 2 :(得分: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

}