Thursday, June 13, 2013

UISegmentedControl in the Navigation Bar with the Back button http://stackoverflow.com/questions/15383014/uisegmentedcontrol-in-the-navigation-bar-with-the-back-button

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

UISegmentedControl in the Navigation Bar with the Back button


I'm adding a UISegmentedControl to the Navigation bar programatically where the titleViewshould be. But as Apple docs have mentioned under titleViewThis 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!

enter image description here

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.

asked Mar 13 at 10:42
Isuru
1,04811031

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

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.

answered Mar 13 at 10:48
CaptainRedmuff
1,316419
Hi 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 andvoila! It works! I don't know why Apple has said it won't work. :S – Isuru Mar 13 at 11:10

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 !!!

No comments:

Post a Comment