How to programmatically add a UISegmentedControl to a container view

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.

Leave a Comment