How can I have a space-filling segmented control in the toolbar in an iOS app?
Asked Answered
T

2

7

I have a segmented control. Whenever the view has finished appearing I create a bar button item to hold it and set that as the toolbars item. The problem I'm having is that the segmented control will not fill up the space in the toolbar, even though it is set to have space-filling behaviour.

How can I have a space-filling segmented control in a toolbar in an iOS app?

To answered 2/5, 2012 at 1:27 Comment(0)
G
1

It sounds like you're trying to get non-standard toolbar behavior out of a UIToolbar. Why not just drop a UIView in there and fill it with a UISegmentedControl in the normal way? Is there some specific functionality of the UIToolbar that you need?

Gules answered 4/5, 2012 at 1:51 Comment(0)
I
0

There is no "space-filling behaviour" for UIViews in general. They get the size they are assigned. All you can do is:

  1. set their autoresizing mask to control how they are resized if their parent view changes its size
  2. set their UIViewContentMode to control how they resize their content (important for UIImageViews, for example)

In your case, you could do the following to get a UIToolbar containing a UISegmentedControl that is as wide as the toolbar:

(void)viewDidLoad
{
    [super viewDidLoad];

    //  Create the toolbar; place it at the bottom of the view.
    UIToolbar *myToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-44, self.view.bounds.size.width, 44)];
    myToolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.view addSubview:myToolbar];

    //  Create the UISegmentedControl with two segments and "Bar" style. Set frame size to that of the toolbar minus 6pt margin on both sides, since 6pt is the padding that is enforced anyway by the UIToolbar.
    UISegmentedControl *mySegmentedControl = [[UISegmentedControl alloc] initWithFrame:CGRectInset(myToolbar.frame, 6, 6)];
    //  Set autoresizing of the UISegmentedControl to stretch horizontally.
    mySegmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    [mySegmentedControl insertSegmentWithTitle:@"First" atIndex:0 animated:NO];
    [mySegmentedControl insertSegmentWithTitle:@"Second" atIndex:1 animated:NO];
    mySegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 

    //  Create UIBarButtonItem with the UISegmentedControl as custom view, and add it to the toolbar's items
    UIBarButtonItem *myBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:mySegmentedControl];
    myToolbar.items = [NSArray arrayWithObject:myBarButtonItem];
}
Insulin answered 9/5, 2012 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.