sallam
sallam

Reputation: 55

UISegmentedControl removing current selected segment when remove segments

i want to add 3 segmentes to UIsegmentedControl and when i tap on the third segment it should remove the first segment and keep selection on the second segment after removing here is code

(void)viewDidLoad {
    [super viewDidLoad];
    //Create label
    label = [[UILabel alloc] init];
    label.frame = CGRectMake(10, 10, 300, 40);
    label.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:label];
    //Create the segmented control
    NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
    segmentedControl= [[UISegmentedControl alloc] initWithItems:itemArray];
    segmentedControl.frame = CGRectMake(35, 200, 250, 50);
    segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
    segmentedControl.selectedSegmentIndex = 1;
    [segmentedControl addTarget:self
                         action:@selector(pickOne:)
               forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentedControl];
}

//Action method executes when user touches the button
-(IBAction)pickOne:(id)sender{


    label.text = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
   [segmentedControl removeSegmentAtIndex:0
                               animated:YES];
    segmentedControl.selectedSegmentIndex=1;

}

Upvotes: 1

Views: 2027

Answers (1)

Duncan C
Duncan C

Reputation: 131418

It isn't clear what you're asking. You want to remove segments from a segmented control and have the control preserve the currently selected segment?

I'm guessing that the segmented control simply un-selects all segments when you remove one.

If you want to preserve the currently selected segment you're probably going to have to write custom logic to do so. Something like this:

  1. Get the currently selected segment.

  2. If it is equal to the index you're deleting, unselect all segments (since the current selection will no longer exist.)

  3. If the current selected segment index < the one you're deleting, re-select that same segment index after deleting a segment

  4. If the current selected index > the one you're deleting, set the selected segment index to 1 less than the previous value after deleting a segment (since all segments after the deleted segment will shift down by 1.)

Upvotes: 1

Related Questions