0

In a custom uitableviewcell, the segmented control is created when the row is created. Each row is a question in a form. Depending on the type of question, the segmented control can have different answers. In the UISegmentedControl reference it only lists the init method as allowing setting all segments at once. Is there a better way than using remove and insert to update the segment to have the pertinent segments?

In the custom UITableView cell's init it has

_answerSegmented = [[UISegmentedControl alloc] init];
[_answerSegmented addTarget:self action:@selector(answerChanged:) forControlEvents:UIControlEventValueChanged];
_answerSegmented.backgroundColor = [UIColor columnHeaderBackground];
[self addSubview:_answerSegmented];

It's not until later that it knows what the segments should be

NSMutableArray *answers = [NSMutableArray arrayWithObjects:@"IN", @"OUT", nil];
if (_question.noItem.boolValue) {
    [answers addObject:@"N/O"];
}
if (_question.naItem.boolValue) {
    [answers addObject:@"N/A"];
}
_answerSegmented.segments = answers; // <---- this line gives a compile error
Austin Haws
  • 364
  • 2
  • 6
  • 15

1 Answers1

5

No, there is no better way. If all segmented controls have the same number of segments then create the control with that number of segments. Then simply use setTitle:forSegmentAtIndex: to change the title of each segment, one at a time.

If the number can change, use removeAllSegments and insertSegmentWithTitle:atIndex:animated:.

Or simply create a new segmented control and remove the old one each time.

rmaddy
  • 314,917
  • 42
  • 532
  • 579