2010-01-19 114 views
14

这似乎没有工作。我究竟做错了什么?试图以编程方式创建rightBarButtonItem

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

史蒂夫的有关观点评论没有负载听起来可能,我都尝试使用setter方法setRightBarButtonItem如果仍然没有按没有工作。 – 2010-01-19 01:11:22

回答

11

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

+0

不工作意味着该按钮不显示在导航栏中。 – 2010-01-19 01:13:52

+0

Steve是对的。请将其加载到-viewDidLoad中。 -awakeFromNib不会在视图控制器中调用 - 只能在UIView类中调用。 – 2010-01-19 04:01:22

+8

史蒂夫和马特都错了。这个代码在'-awakeFromNib'中很好,当且仅当VC本身实际上是从一个nib加载的。马特,'-awakeFromNib'在每个由nib创建的对象上调用,包括VC的。最有可能的是VC本身不在笔尖,但它使用笔尖,因此Sam的困惑。在这种情况下,它应该放在'-initWithNibName:bundle:'中。 – 2011-02-11 20:54:11

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 

} 
+3

为什么没有必要明确地发布这个,只是出于好奇? – diatrevolo 2011-04-06 15:30:08

+1

因为它是autoreleased。 – pt2ph8 2011-07-09 23:12:19

21

我的猜测是,您添加到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

这对我来说很重要,我试图将按钮分配给导航控制器,而不是rootViewController。这应该是被接受的答案。 – 2012-09-17 06:02:10

+0

太棒了!!.... – 2016-02-26 09:26:40