将UIBarButtonItem添加到UINav..Controller

时间:2010-03-26 02:55:44

标签: objective-c iphone uinavigationcontroller uibarbuttonitem

我不确定我在这里缺少什么。我有自定义UINavigationController,我正在尝试向条形图添加持久性UIBarButtonItem

-(void)viewDidLoad
{
    self.navigationBar.barStyle = UIBarStyleBlack;
    UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithTitle:@"Nope..."
               style:UIBarButtonItemStyleBordered
                 target:self
                 action:@selector(goBack:)]; 
    self.navigationItem.leftBarButtonItem =bbi;
    [bbi release]; 
}
-(void)goBack:(id)sender
{
    NSLog(@"go back now");
}

我在这里失踪了什么? - 顺便说一句,我不想​​/不会使用IB。

更新: 目前这是我能得到的最接近的:

-(void)viewDidLoad
{
    self.navigationBar.barStyle = UIBarStyleBlack;
    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];
    navBar.barStyle = UIBarStyleBlack;
    UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:@"Currently Playing..."];
    [navBar pushNavigationItem:navItem animated:NO];
    UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStyleBordered target:self action:@selector(goBack:)];
    navItem.rightBarButtonItem = editButton;

    [self.view addSubview:navBar];

    [editButton release];
    [navItem release];
    [navBar release]; 
    [super viewDidLoad];
}

可怕的是我必须将整个导航栏添加到已经有导航栏的UINavigationController ....如果我尝试使用现有的,我会收到此错误:

'NSInternalInconsistencyException', reason: 'Cannot call pushNavigationItem:animated: directly on a UINavigationBar managed by a controller.'

...真???

1 个答案:

答案 0 :(得分:22)

不能在navigationItem实例上设置{p> UINavigationController,而是在导航控制器“内部”显示的view视图控制器上设置。

如果您的控制器本身被推入另一个导航控制器,则导航控制器上的self.navigationItem设置将会起作用。