在UINavigationBar中看不到UIBarButtonItem时该怎么办?

时间:2011-02-04 12:29:03

标签: iphone uinavigationcontroller uibarbuttonitem

大家好 我在ViewDidLoad中编写一个简单的代码,类是UITableViewController的子代,如下所示,但是按钮不可见,而标题是可见的,

我在ViewDidLoad方法ViewController.m中点击按钮的另一件事,就是调用方法,该方法的代码如下所示

//Code of button target method

-(void)statusMethod {
    NSLog(@"statusMethod");
    Status *ob=[[Status alloc]init];
    [self presentModalViewController:ob animated:YES];

}

//Code of ViewDidLoad of Status.m
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, width, 43)];
    navBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:navBar];
    [navBar release];

UIBarButtonItem *home = [[UIBarButtonItem alloc] initWithTitle:@"HOME" style:UIBarButtonItemStylePlain target:self action:@selector(homeMethod)];
self.navigationItem.rightBarButtonItem = home;

UIBarButtonItem *add = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonSystemItemAdd target:self action:@selector(addMethod)]; 
self.navigationItem.leftBarButtonItem = add;


UILabel *label = [[UILabel alloc] initWithFrame:
                  CGRectMake(10,10,width-20,25)];
label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
label.text = @"Status";
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont systemFontOfSize:25];
label.textAlignment = UITextAlignmentCenter;
[navBar addSubview:label];
[label release];

任何想法,代码中有什么问题? 我不明白,你可以再问我一次, 我会赞美,如果我能解决我的问题

1 个答案:

答案 0 :(得分:4)

看起来self.navigationItem仅由UINavigationController(控制器,而不是bar)查看。酒吧本身不打算检查。

所以你应该

1)使用真正的UINavigationController,它带有自己的navigationBar,并将为您处理navigationItems。上面的self.navigationItem代码将适用于该情况。 (你应该考虑self.navigationItem.title = @"Status";

如果你的UITableViewController要在导航堆栈上打开和关闭东西,这就是你应该采用的路径。

2)使用UINavigationBar自己的导航项。除了它似乎没有一个导航项,所以你必须添加自己的:

UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:@"Status"];

[navBar setItems:[NSArray arrayWithObject:navItem]];
[navItem release];

然后将左右按钮设置为

[navBar topItem].leftBarButtonItem = add;
[add release];

[navBar topItem].rightBarButtonItem = home;
[home release];

处理UINavigationController / UINavigationBar / UINavigationItem可能令人困惑,但幸运的是,Apple对UINavigationController documentation顶部的所有这些内容如何协同工作有一个很好的解释。