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

前端 未结 3 942
后悔当初
后悔当初 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: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.

提交回复
热议问题