UISegmentedControl in the Navigation Bar with the Back button

Deadly 提交于 2019-12-03 07:15:31

问题


I'm adding a UISegmentedControl to the Navigation bar programatically where the titleView should be. But as Apple docs have mentioned under titleView, This property is ignored if leftBarButtonItem is not nil.

But I want to have the back button as well. Like they have illustrated in their own images!

Below is the code I add the 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;

Is there another way to add a UISegmentedControl along with the Back button as well?

Thank you.


回答1:


Try this

Remove this line --- > self.navigationItem.leftBarButtonItem = nil;

Add this instead

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

Only change is I have added this line :

[statFilter sizeToFit];

Hope this Helps !!!




回答2:


You can create a UIBarButtonItem with a custom view which could potentially be your UISegmentedControl.

Something along the lines of the following may work.

//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];

I haven't tested this but it should be along the right lines of what you need.



来源:https://stackoverflow.com/questions/15383014/uisegmentedcontrol-in-the-navigation-bar-with-the-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!