How can I set the width of the UISegmentControl in the UINavigationBar to its maximum width dynamically?
This is the code I am currently using. Unfortunately UISegmentControl is not the maximum width for the panel. Is there a quick and easy way to make it as wide as possible in code without requiring an exact frame width to set it?
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;
This is what it looks like now:
Here's what I want it to look like:
source to share
While this is a bit hacky and without knowing all the behavior you are looking for (like what happens when it rotates?), I didn't immediately see a way to set the width correctly. Try this and / or change it according to 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;
This gives the following output for iPhone and iPad:
EDIT: Some things worth noting, it doesn't seem like your code is using ARC, which I would highly recommend , you used setSegmentedControlStyle which is deprecated in iOS7 and it's easier / cleaner to create an NSArray there:
NSArray *array = @[object1, object2];
// the above is much cleaner than
NSArray *array = [NSArray arrayWithObjects:object1, object2, nil];
source to share