I’ve got a UITableView with custom UITableCells. Inside those UITableCells are UISegmentedControls. I’m trying to change the tint color of just the first UISegment. This works correctly until the UITableCell is reused through dequeueReusableCellWithIdentifier. When reused UITableCells begin to appear when scrolling down, the last segment is tinted blue rather than the first. Here is the relevant code in cellforRowAtIndexPath:
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CellIdentifier = @"CustomCell";
CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[CustomTableCell alloc] init];
}
[cell.segmentedControl setTintColor:GRAY_COLOR];
[[[cell.segmentedControl subviews] objectAtIndex:0] setTintColor:BLUE_COLOR];
...
return (UITableViewCell *) cell;
}
This UISegmentedControl’s UISegmentedControlStyle is UISegmentedControlStyleBar, if that matters.
You are digging into the undocumented subview structure of a segmented control. There is no public API to tint one segment as you are. What happens when the implementation changes in the future and the subview you are getting doesn’t respond to the ‘setTintColor:’ method?
You are also relying on the order of the subviews. The order can change. The implementation of the segmented control can move subviews to the back or front over time. You can’t assume that subview 0 is the view for the first segment.
Your best approach here is to subclass UISegmentedControl or create your own custom control that properly make a segment a specific color.