15

我正在以編程方式將UISegmentedControl添加到導航欄,其中titleView應該是。但是Apple docstitleView,中提到,如果leftBarButtonItem不是零,則該屬性將被忽略帶有後退按鈕的導航欄中的UISegmentedControl

但我想要後退按鈕。就像他們已經在他們自己的圖像中展示的一樣

enter image description here

下面是我添加UISegmentedControl代碼。

self.navigationItem.leftBarButtonItem = nil; 
UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Filter_Personnal", @"Filter_Department", @"Filter_Company", nil]; 
[statFilter setSegmentedControlStyle:UISegmentedControlStyleBar]; 
self.navigationItem.titleView = statFilter; 

有另一種方式與後退按鈕旁邊加上UISegmentedControl呢?

謝謝。

回答

3

您可以使用自定義視圖創建UIBarButtonItem,該視圖可能是您的UISegmentedControl

下面的一些內容可能會起作用。

//create segmented control with items 
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"One", @"Two", nil]]; 

//create bar button item with segmented control as custom view 
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl]; 

//add segmented control bar button item to navigation bar 
[[[self navigationController] navigationItem] setRightBarButtonItem:barButtonItem]; 

我沒有測試過這個,但它應該沿着你所需要的正確路線。

+0

嗨,感謝您的回覆。在此期間,我在等待,我打了一個小程序來測試它。我把2個視圖控制器,第一個按鈕,以繼續對另一個。在第二個View Controller的ViewDidLoad方法中,我使用我在我的問題中發佈的代碼和[voila](http://i.imgur.com/DlZuAwk.png)創建了UISegmentedControl!有用!我不知道蘋果爲什麼說它不起作用。 :S – Isuru 2013-03-13 11:10:14

23

試試這個

刪除此行--->self.navigationItem.leftBarButtonItem = nil;

添加這個代替

UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Filter_Personnal", @"Filter_Department", @"Filter_Company", nil]]; 
[statFilter setSegmentedControlStyle:UISegmentedControlStyleBar]; 
[statFilter sizeToFit]; 
self.navigationItem.titleView = statFilter; 

唯一不變的是我已經加入這一行:

[statFilter sizeToFit]; 

希望這幫助!

+0

這實際上幫了我,謝謝... :) :) – tausun 2013-09-26 05:44:46

+9

'setegmentedControlStyle'從iOS7開始已棄用...你能更新你的答案嗎? – 2013-11-14 00:37:03

+0

這似乎不適用於通過IBOutlet添加段控制。段控制工作以編程方式完美添加。 – Cymric 2015-06-30 07:03:07