UISegmentedControl再次按下取消选择段

bha*_*tsb 2 uisegmentedcontrol ios

如何通过再次按相同的段来取消选择UISegmented控件中的给定段?

例如按段0,它将被选中并保持高亮显示.再次按段0,它将变为未选中且未突出显示.

该控件仅触发UIControlEventValueChanged事件.其他事件似乎不适用于它.

有一个属性'瞬间',当设置为YES时几乎允许上述行为,除了突出显示只是暂时的.当momentary = YES按两次相同的段时会导致两个UIControlEventValueChanged事件,但是当momentary = NO时,只有第一次按下给定的段会导致触发UIControlEventValueChanged事件.即,在同一段上的后续按下将不会触发UIControlEventValueChanged事件.

pro*_*ace 9

你可以继承UISegmentedControl:

斯威夫特3

class ReselectableSegmentedControl: UISegmentedControl {

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let previousSelectedSegmentIndex = self.selectedSegmentIndex

        super.touchesEnded(touches, withEvent: event)

        if previousSelectedSegmentIndex == self.selectedSegmentIndex {
            if let touch = touches.first {
                let touchLocation = touch.locationInView(self)
                if CGRectContainsPoint(bounds, touchLocation) {
                    self.sendActionsForControlEvents(.ValueChanged)
                }
            }
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

斯威夫特4

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    let previousSelectedSegmentIndex = self.selectedSegmentIndex

    super.touchesEnded(touches, with: event)

    if previousSelectedSegmentIndex == self.selectedSegmentIndex {
        let touch = touches.first!
        let touchLocation = touch.location(in: self)
        if bounds.contains(touchLocation) {
            self.sendActions(for: .valueChanged)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后

 @IBAction func segmentChanged(sender: UISegmentedControl) {
    if (sender.selectedSegmentIndex == selectedSegmentIndex) {
        sender.selectedSegmentIndex =  UISegmentedControlNoSegment;
        selectedSegmentIndex = UISegmentedControlNoSegment;
    }
    else {
        selectedSegmentIndex = sender.selectedSegmentIndex;
    }
}
Run Code Online (Sandbox Code Playgroud)