Thursday, July 14, 2011

How to add UISegmentControl to UIToolBar ? (programmatically)

Here is the code snippet. Toolbar is the UIToolBar, This  where you want to add your segmentBar.This code also gives you an idea about using  spaces between toolbar items.

      UIBarButtonItem *refresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshClicked:) ];
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    NSArray *statusItems = [[NSArray alloc] initWithObjects:@"Girls",@"Boys", nil];
    UISegmentedControl *bottomSegmentBar = [[UISegmentedControl alloc] initWithItems:statusItems];
    [bottomSegmentBar addTarget:self action:@selector(segmentBarClicked:) forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem *SegmentItem = [[UIBarButtonItem alloc] initWithCustomView:bottomSegmentBar];              
    NSArray *toolbarItems = [[NSArray alloc] initWithObjects:flex,SegmentItem,flex,refresh,nil];
    Toolbar.items = toolbarItems;

1 comment:

  1. Is segmented control in your app vertically centered? I have similar code, but segmented control's origin.y automatically set to 8, so it is 1px shifted down. But I need to center it.