2011-07-27 57 views
1

如何在UINavigationItem中添加UISegmentedControl? 我想創建一個帶有段控件的UINavigationBar,它添加了導航欄的標題。如何在UINavigationItem ..中添加UISegmentControl?

UISegmentedControl有兩個索引。

這是我有:

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:[UIImage imageNamed:@"grid.png"],[UIImage imageNamed:@"list.png"],nil]]; 
    [segmentedControl addTarget:self action:@selector(segmentedAction) forControlEvents:UIControlEventValueChanged]; 
    segmentedControl.frame = CGRectMake(0, 0, 90, 40); 
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
    segmentedControl.momentary = YES; 
    [segmentedControl setTintColor:[UIColor clearColor]]; 

    UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];  
    self.navigationItem.rightBarButtonItem = segmentBarItem; 

我已經把它放在右邊。所以,也要放在導航欄的中間。

這不起作用,請讓我知道如果我做錯了什麼。

感謝

+1

一種方法是使用下面的代碼:HTTP://計算器.com/questions/6828270/uinavigationbar -with-two-buttons-on-the-left/6828577#6828577和改變框架的起源,所以它開始在中間。 – Jano

+0

坦克Jano ..它的工作 –

回答

1

就快,你只需要分段控件添加到UINavigationItem並添加到您的UINavigationBar的:

// This code is used for a custom navigation bar 

UINavigationItem* newItem = [[UINavigationItem alloc] initWithTitle:@""]; 
[newItem setTitleView:segmentedControl]; 

// Assuming you already have a navigation bar called "navigationBar" 
[navigationBar setItems:[NSArray arrayWithObject:newItem] animated:NO]; 

// No memory leaks please... 
[newItem release]; 

,或者如果您希望使用現有的控制器

// This is used for an existing navigation controller 
[navigationController.navigationBar.topItem setTitleView:segmentedControl]; 
// or if you want to access through the root view controller of the nav controller 
[rootController.navigationItem setTitleView:segmentedControl]; 

這應該將導航欄的中心視圖設置爲分段控件。

希望我能幫上忙!

編輯:如果你需要更多的幫助,這些類的蘋果文檔相當透徹:做

UINavigationItem

UINavigationBar

+0

我的課程已經導航基類..所以它給這樣的錯誤'不能調用setItems:animated:直接在由控制器管理的UINavigationBar上。'... –

+0

我添加了代碼來支持現有的導航控制器。讓我知道它是如何工作的。 – foslock

+0

看到這個鏈接.. http://stackoverflow.com/questions/6828270/uinavigationbar-with-two-buttons-on-the-left/6828577#6828577現在它工作 –

相關問題