想要更改导航栏标题

5

我已经将我的第一个视图嵌入到了NavigationController中,并将segue设置为推送。 我想在每个视图中更改导航栏的标题以显示某些内容,并通过我的代码更新它。 我尝试像这样调用导航控制器:

self.navigationController.navigationBar.topItem.title = @"YourTitle";

但是这样不起作用,我该怎么做?

5个回答

14

导航控制器从视图控制器获取标题,因此这将完成工作

- (void)viewDidLoad {

   [super viewDidLoad];
   self.title = @"Some Title";
}

5
这对我很有效:
self.navigationItem.title = @"YourTitle"; 

希望这能有所帮助。

在添加了导航项之后,您应该使用这个解决方案;如果您没有添加任何导航项,您可以简单地使用:self.title。谢谢。 - Isaac Bosca

2
self.title = @"My Title"

这将更改导航栏的标题以及引用此视图控制器的标题元素(例如选项卡栏等)。
self.navigationItem.title = @"My Title";

这将仅更改当前视图控制器导航栏的标题。

0

您也可以替换标题视图:

UIView* titleView = [[UIView alloc] init];
[self.navigationItem setTitleView: titleView];

0
如果只更改导航栏标题,则尝试在initWithNibName方法中进行。
        self.title=@"your title";

但如果您想要为标题设置颜色或字体大小,则需要在其上放置一个UILabel。

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];

        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:20.0];
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = UITextAlignmentCenter;

        label.textColor = [UIColor blackColor];
        self.navigationItem.titleView = label;
        label.text =@"your title";
        [label sizeToFit];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接