UISegmentedControl in the Navigation Bar with the Back button
Solution 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 !!!
Solution 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.
Isuru
Started out as a C# developer. Turned to iOS in 2012. Currently learning SwiftUI. Loves fiddling with APIs. Interested in UI/UX. Want to try fiddling with IoT. Blog | LinkedIn
Updated on June 05, 2022Comments
-
Isuru almost 2 years
I'm adding a
UISegmentedControl
to the Navigation bar programatically where thetitleView
should be. But as Apple docs have mentioned undertitleView
, 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.
-
Isuru about 11 yearsHi thanks for the response. In the meantime I was waiting, I slapped together a small program to test it out. I put 2 View Controllers, a button in the first one to segue to the other one. And in the ViewDidLoad method of the second View Controller, I created the UISegmentedControl using the code I've posted in my question and voila! It works! I don't know why Apple has said it won't work. :S
-
Arian Faurtosh over 10 years
setegmentedControlStyle
is deprecated as of iOS7... can you update your answer please? -
Cymric almost 9 yearsThis doesn't seems to work with segment control add via a IBOutlet. A segment control work added programatically work perfectly.