Specifying UISegmentedControlNoSegment to UISegmentedControl's selectedSegmentIndex has no Effect on iOS 13

前端 未结 3 922
后悔当初
后悔当初 2020-12-20 18:25

I am the maintainer of STAControls which subclasses various UIControls, one of which is UISegmentedControl. Within that project\'s sample app, I ha

相关标签:
3条回答
  • 2020-12-20 19:16

    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.

    0 讨论(0)
  • 2020-12-20 19:19

    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.

    0 讨论(0)
  • 2020-12-20 19:30

    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()
    
    0 讨论(0)
提交回复
热议问题