I am the maintainer of STAControls which subclasses various UIControl
s, one of which is UISegmentedControl
. Within that project\'s sample app, I ha
Resolved and added a work around in STASegmentedControl. I did the following:
- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex {
if (@available(iOS 13.0, *)) {
if (selectedSegmentIndex == UISegmentedControlNoSegment && self.selectedSegmentIndex >= 0
&& !self.handlingNoSegment)
{
self.handlingNoSegment = YES;
NSUInteger index = self.selectedSegmentIndex;
NSString *title = [self titleForSegmentAtIndex:self.selectedSegmentIndex];
[self removeSegmentAtIndex:self.selectedSegmentIndex animated:NO];
[self insertSegmentWithTitle:title atIndex:index animated:NO];
}
self.handlingNoSegment = NO;
}
[super setSelectedSegmentIndex:selectedSegmentIndex];
}
Consult this link for the entire commit.
Remove the segment, then create it again. Here's a version in Swift, which only works if you've got text segments (not images). It assumes you've got an Storyboard with a segmented control and a button.
class ViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBAction func clearSegmentedControl(_ sender: Any) {
guard segmentedControl.selectedSegmentIndex >= 0 else {
return
}
let index = self.segmentedControl.selectedSegmentIndex
let title = self.segmentedControl.titleForSegment(at: index) ?? ""
self.segmentedControl.removeSegment(at: self.segmentedControl.selectedSegmentIndex, animated: false)
self.segmentedControl.insertSegment(withTitle: title, at: index, animated: false)
self.segmentedControl.selectedSegmentIndex = UISegmentedControl.noSegment
}
}
In the Simulator, I couldn't see any flickering. After removing such a selected segment, selectedSegmentIndex becomes -2. This is a bit weird so that's why I added the last line of code, which sets it to the noSegment
constant.
The solutions given in the other answers are overblown. There is a much simpler workaround: just call setNeedsLayout
on the segmented control.
self.seg.selectedSegmentIndex = UISegmentedControl.noSegment
self.seg.setNeedsLayout()