如何通过再次按下同一段来取消选择 UISegmented 控件中的给定段?
例如按下段 0,它将被选中并保持突出显示。再次按下段 0,它将变为未选中且未突出显示。
该控件仅触发 UIControlEventValueChanged 事件。其他事件似乎不适用于它。
有一个属性 'momentary' 当设置为 YES 时几乎允许上述行为,除了突出显示只是暂时的。当 momentary=YES 按下同一段两次会导致两个 UIControlEventValueChanged 事件,但当 momentary=NO 时,只有第一次按下给定段会导致 UIControlEventValueChanged 事件被触发。 IE。对同一段的后续按下不会触发 UIControlEventValueChanged 事件。
最佳答案
你可以继承 UISegmentedControl:
swift 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)
}
}
}
}
}
swift 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)
}
}
}
然后
@IBAction func segmentChanged(sender: UISegmentedControl) {
if (sender.selectedSegmentIndex == selectedSegmentIndex) {
sender.selectedSegmentIndex = UISegmentedControlNoSegment;
selectedSegmentIndex = UISegmentedControlNoSegment;
}
else {
selectedSegmentIndex = sender.selectedSegmentIndex;
}
}
关于ios - UISegmentedControl 再次按下取消选择段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092101/