设置UINavigationBar的标题

6

在视图加载后设置self.navigationItem.title = @"MyTitle";是否可行?

我正在使用搜索栏,同时在同一视图中使用搜索结果填充UITableView。因此,我想在搜索结果加载后将搜索栏的文本值设置为导航栏的标题。

我正在使用iOS 4.3。


2
为什么不试一试,你就会知道是的,是的,是的,它会起作用... - Inder Kumar Rathore
1
我不是没有尝试过就问问题。是的,我已经尝试过了。但是我没有找到解决方案。这就是为什么我会问这个问题的原因。 - chinthakad
然后尝试使用 self.title = @"MyTitle"; - Inder Kumar Rathore
是的,我尝试了两种方法。但都没有起作用。 - chinthakad
7个回答

15

只需像这样设置UINavigationBar的标题:

navBar.topItem.title = @"sample string";

2

我找到了一个解决方案。我按照Pedro Valentini的帖子所说进行操作。

这是我所做的:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
label.textAlignment = UITextAlignmentCenter;
[label setFont:[UIFont boldSystemFontOfSize:16.0]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextColor:[UIColor whiteColor]];
[label setText:text];
[self.navigationController.navigationBar.topItem setTitleView:label];
[label release]; 

这个解决方案将忽略现有导航栏的设计属性,因为您正在设置自己的标签。如@SamirChen所述,将navBar.topItem.title设置为更直接,并且将利用已经设置好的设计。 - Jay Whitsitt

2

通常,titleView 将是一个 UILabel,因此您可以获取它、转换它并设置其文本。

由于某些原因,我在 viewDidLoad 中使用它时遇到了问题,在将其添加到 viewWillAppear 中似乎行得通。

((UILabel *)self.navigationController.navigationBar.topItem.titleView).text = @"your title here"

一些解释会帮助这个答案。 - dove

1

可以。您可以在UIViewController的任何生命周期中动态设置navigationItem的标题。设置操作由getter方法处理,该方法向UINavigationController发送消息以上传导航栏的视图内容以反映新标题。


0

如果self在“inside”一个UINavigationController中,那应该可以工作。


在我的应用程序委托中,我执行以下操作:UINavigationController *rootViewNavigationController = [[UINavigationController alloc] initWithRootViewController:self.rootViewController]; rootViewController是我将要动态更改标题的那个。 - chinthakad

0
_navBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
_navBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
UINavigationItem *navItem = [UINavigationItem alloc];
navItem.title = @"Title";

试试这个。


0
    self.navigationItem.title = @"Terms and Conditions";

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