使用“后退”按钮在导航栏中进行UISegmentedControl

时间:2013-03-13 10:42:11

标签: ios objective-c uinavigationcontroller uinavigationbar uisegmentedcontrol

我正在以编程方式在导航栏中添加UISegmentedControl titleView。但正如Apple docstitleView下提到的那样,如果leftBarButtonItem不是nil ,则会忽略此属性。

但我也想要后退按钮。就像他们在自己的图像中说明一样!

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以及后退按钮吗?

谢谢。

2 个答案:

答案 0 :(得分: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];

希望这有助于!!!

答案 1 :(得分: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];

我没有对此进行测试,但它应该与您需要的正确相符。