2013-09-28 133 views
0

任何人都可以幫助我如何使用標題視圖屬性將兩個按鈕添加到導航標題視圖。我試過,但能夠使用下面的代碼只能添加一個按鈕。如何將兩個按鈕添加到UINavigation欄標題視圖

UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
customView.backgroundColor = [UIColor redColor]; 

UIButton *b1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
UIButton *b2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 

[b1 setTitle:@"Hai" forState:UIControlStateNormal]; 
[b2 setTitle:@"Hello" forState:UIControlStateNormal]; 

[customView insertSubview:b1 atIndex:0]; 
[customView insertSubview:b2 atIndex:1]; 

self.navigationItem.titleView = customView; 
+0

什麼關於我的這個答案嘗試這個,你做了一些MINORE錯誤看看這個http://stackoverflow.com/問題/ 16958913 /如何添加項目在uinavigationbar特定位置/ 16959449#16959449 –

回答

0

使用此代碼:

UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)]; 
customView.backgroundColor = [UIColor redColor]; 

UIButton *b1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
UIButton *b2 = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, 50, 50)]; 

[b1 setTitle:@"Hai" forState:UIControlStateNormal]; 
[b2 setTitle:@"Hello" forState:UIControlStateNormal]; 

[customView insertSubview:b1 atIndex:0]; 
[customView insertSubview:b2 atIndex:1]; 

self.navigationItem.titleView = customView; 

輸出:

Example image of output

+0

你檢查了我的答案嗎? –

+0

通過插入子視圖來查看我的編輯我收到以下異常。 – srinu

+0

爲什麼-1?讓我知道理由 –

0

這是因爲您已經爲兩個按鈕添加了相同的框架。所以,按鈕實際上是重疊的。您應該使用此代碼:

UIButton *b1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)]; 
UIButton *b2=[[UIButton alloc]initWithFrame:CGRectMake(60, 0, 50, 50)]; 

然後,您可以簡單地將這些按鈕添加到您的自定義視圖。

[cusotmView addSubView:b1]; 
[cusotmView addSubView:b2]; 

錯誤原因:

你不能直接添加UIButtons。你需要先把它們包裝成UIBarButtonItems

示例代碼:

UIBarButtonItem *btn1 = [[UIBarButtonItem alloc] initWithCustomView:b1]; 
UIBarButtonItem *btn2 = [[UIBarButtonItem alloc] initWithCustomView:b2]; 
[cusotmView addSubView:btn1]; 
[cusotmView addSubView:btn2]; 
+0

我試過你的代碼,但沒有運氣我得到異常像 - [UIButton isSystemItem]無法識別的選擇器發送舉例來說。 – srinu

+0

@srinu:檢查我的答案中的更新。 – Bhavin