2012-12-30 21 views
2

我正在嘗試將UISegmentedControl添加到僅有一個視圖(而不是整個視圖控制器)的UINavigationBar的中間。我怎麼能這樣做呢?向UINavigationBar的中心添加分段控件

其他答案我只讀允許整個視圖控制器包含一個UINavigationItem作爲標題。我需要它只在一個視圖上顯示。

+1

按照我的答案http://stackoverflow.com/questions/13890380/addimg-mutiple-button-on-navigation-bar-in-iphone-sdk/13890404#13890404 – Rajneesh071

+0

http://stackoverflow.com/questions/ 13565962/how-to-programmetically-add-navigation-bar-and-back-button-on-it/13619760#13619760 – Rajneesh071

+0

@ Rajneesh071你從其他問題的答案沒有回答我的問題。還是你建議我在導航欄上畫一個視圖? – Jay

回答

4

此代碼將幫助您。這段代碼的

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems: 
              [NSArray arrayWithObjects:@"Add",@"Delete", 
              nil]]; 
    segmentedControl.frame = CGRectMake(0, 0, 80, 30); 
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
    [segmentedControl setWidth:35.0 forSegmentAtIndex:0]; 
    [segmentedControl setWidth:45.0 forSegmentAtIndex:1]; 

    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged]; 
    segmentedControl.momentary = YES; 

    UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl]; 
    [segmentedControl release]; 

    self.navigationItem.leftBarButtonItem = segmentBarItem; 
    [segmentBarItem release]; 

結果是

enter image description here

編輯:

確切的代碼,將工作:

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems: 
              [NSArray arrayWithObjects:@"Add",@"Delete", 
              nil]]; 
    segmentedControl.frame = CGRectMake(0, 0, 80, 30); 
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
    [segmentedControl setWidth:35.0 forSegmentAtIndex:0]; 
    [segmentedControl setWidth:45.0 forSegmentAtIndex:1]; 

    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged]; 
    segmentedControl.momentary = YES; 

    self.navigationItem.titleView = segmentedControl; 
+0

我只是用'self.navigationItem.leftBarButtonItem = segmentControl;'而不是和它的工作。謝謝!我將在爲我工作的代碼中進行編輯。 – Jay

3

可以作爲子視圖添加您的UISegmentedControl到你的navigati的OnBar。

NSArray *arrayOfItems = [[NSArray alloc] initWithObjects:@"A",@"B",@"C", nil]; 
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:arrayOfItems]; 
segmentedControl.frame=CGRectMake(60, 0, 200, 44); 
[self.navigationController.navigationBar addSubview:segmentedControl]; 
1

如果要添加中心的任何視圖一個UISegmentedControl,不僅UINavigationView:

UISegmentedControl *segmentedTab = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"a", @"b", @"c", nil]]; 
segmentedTab.center = CGPointMake(segmentedView.frame.size.width/2, segmentedView.frame.size.height/2); 
[self.segmentedView addSubview:segmentedTab]; 

哪裏segmentedView是將包含我們UISegmentedControl的視圖。

相關問題