2012-03-23 63 views
6

在視圖加載後可以設置self.navigationItem.title = @"MyTitle";嗎?設置UINavigationBar的標題

我正在使用搜索欄,並在同一視圖中使用搜索結果提供UITableView。所以我想在搜索結果加載後,將搜索欄的文本值設置爲導航欄的標題。

我正在使用iOS 4.3。

+2

爲什麼你不試一試,你會知道是的是的,它會工作... – 2012-03-23 14:12:49

+1

我不問沒有嘗試過它。是的,我嘗試過。但我找不到解決方案。這就是我問這個的原因。 – chinthakad 2012-03-23 14:30:21

+0

然後嘗試'self.title = @「MyTitle」;' – 2012-03-23 14:44:17

回答

2

找到了解決方案。我跟着Pedro Valentini's post

這是我做的,

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]; 
+0

由於您正在設置自己的標籤,因此此解決方案將忽略現有導航欄的設計屬性。 @SamirChen所說的將navBar.topItem.title設置爲更直接,並且將利用已經設置好的設計。 – 2017-04-26 21:14:08

0

這應該工作,如果自己在「內」a UINavigationController

+0

在我的應用程序委託,我確實遵循,UINavigationController * rootViewNavigationController = [[UINavigationController alloc] initWithRootViewController:self.rootViewController]; rootViewController是我要動態更改標題的一個。 – chinthakad 2012-03-23 14:44:35

+0

那應該工作得很好,那麼! – Max 2012-03-23 14:58:10

1

是的。您可以在UIViewController的生命週期的任何部分期間動態設置navigationItem的標題。 set操作由getter方法處理,該方法向UINavigationController發送消息以上傳導航欄的視圖內容以反映新標題。

15

剛剛成立的UINavigationBar標題是這樣的:

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

通常情況下,titleview的將是一個的UILabel,所以你可以把它拿來,投它,並設置其文本。

由於某種原因,我在使用viewDidLoad時遇到了問題,因此將其添加到viewWillAppear似乎有訣竅。

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

一些解釋將有助於這個答案 – dove 2012-12-20 12:24:55

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";