Ethan Allen Ethan Allen - 2 months ago 8
iOS Question

How do I set the width of a UISegmentControl in a UINavigationBar to maximum width dynamically?

This is the code I am currently using. Unfortunately the UISegmentControl isn't max width for the bar. Is there a quick and easy way to make it the max width in code without needing an exact frame width to set it to?

UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(addItem:)] autorelease];
self.navigationItem.rightBarButtonItem = addButton;


UISegmentedControl *segBar = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"First", @"Second", @"Third", nil]] autorelease];
[segBar setSegmentedControlStyle:UISegmentedControlStyleBar];
[segBar sizeToFit];
self.navigationItem.titleView = segBar;


Here is what it currently looks like:

enter image description here

Here is what I want it to look like:

enter image description here

Answer

While this is slightly hackish and not knowing the entire behavior you're looking for (like what happens when it rotates?), I didn't immediately see a way to set the widths nicely. Try this out and/or alter it to fit your needs:

// this takes the width of the view, gets 80% of that width (to allow for space to the left of the nav button) and
// divides it by 3 for each individual segment
CGFloat approxWidth = (CGRectGetWidth(self.view.frame) * .80) / 3;
[[UISegmentedControl appearance] setWidth:approxWidth forSegmentAtIndex:0];
[[UISegmentedControl appearance] setWidth:approxWidth forSegmentAtIndex:1];
[[UISegmentedControl appearance] setWidth:approxWidth forSegmentAtIndex:2];

// create the segmented control and set it as the title view
UISegmentedControl *segBar = [[UISegmentedControl alloc] initWithItems:@[@"First", @"Second", @"Third"]];
self.navigationItem.titleView = segBar;

That produces the following result for iPhone and iPad:

enter image description here enter image description here

EDIT: It's worth noting a few things as well, it doesn't look like your code is using ARC, which I would highly recommend, you were using setSegmentedControlStyle, which is deprecated in iOS7, and there's an easier/cleaner way to create an NSArray:

NSArray *array = @[object1, object2];

// the above is much cleaner than
NSArray *array = [NSArray arrayWithObjects:object1, object2, nil];
Comments