How to programmatically add a UISegmentedControl to a container view

Alede picture Alede · Jul 14, 2011 · Viewed 90.2k times · Source

How would I define the frame for a UISegmentedControl? I would like the segmented control to appear at the bottom of a container view i.e UIView.

Answer

Muhammad Rizwan picture Muhammad Rizwan · Jul 14, 2011

this one is perfect I tested.....

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 435)];
scroll.contentSize = CGSizeMake(320, 700);
scroll.showsHorizontalScrollIndicator = YES;

NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(35, 200, 250, 50);
segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
[segmentedControl addTarget:self action:@selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
segmentedControl.selectedSegmentIndex = 1;     
[scroll addSubview:segmentedControl];
[segmentedControl release]; 
[self.view addSubview:scroll];

Then add your method in your class.

- (void)MySegmentControlAction:(UISegmentedControl *)segment 
{    
    if(segment.selectedSegmentIndex == 0)
    {
        // code for the first button
    } 
}

For deprecated UISegmentedControlStyle you can take a look on this URL.