如何通过再次按相同的段来取消选择UISegmented控件中的给定段?
E.g。按段0,它将被选中并保持高亮显示。再次按段0,它将被取消选中并且不会突出显示。
该控件仅触发UIControlEventValueChanged事件。其他事件似乎不适用于它。
有一个属性'瞬间',当设置为YES几乎允许上述行为时,除了突出显示只是暂时的。当momentary = YES按两次相同的段时会导致两个UIControlEventValueChanged事件,但是当瞬间= NO时,只有第一次按下给定的段会导致触发UIControlEventValueChanged事件。即后续按下同一段不会触发UIControlEventValueChanged事件。
答案 0 :(得分:6)
你可以继承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;
}
}
答案 1 :(得分:0)
并不是您所要的,但我正在寻找类似的功能并决定了这一点。
向UISegmentedControl添加doubleTap手势,以设置selectedSegmentIndex
初始化UISegmentedControl时。
let doubleTap = UITapGestureRecognizer(target: self, action #selector(YourViewController.doubleTapToggle))
doubleTap.numberOfTapsRequired = 2
yourSegmentedControl.addGestureRecognizer(doubleTap)
取消选择细分的功能
@objc func doubleTapToggle () {
yourSegmentedControl.selectedSegmentIndex = -1
yourSegmentedControl.sendActions(for: valueChanged)
}
答案 2 :(得分:0)
基于@protspace答案,这是一种更简单的方法,而无需在@IBAction
中编写任何内容:
class DeselectableSegmentedControl: UISegmentedControl {
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let previousSelectedSegmentIndex = selectedSegmentIndex
super.touchesEnded(touches, with: event)
if previousSelectedSegmentIndex == selectedSegmentIndex {
let touch = touches.first!
let touchLocation = touch.location(in: self)
if bounds.contains(touchLocation) {
selectedSegmentIndex = UISegmentedControl.noSegment
sendActions(for: .valueChanged)
}
}
}
}
答案 3 :(得分:-1)
可以使用@IBOutlet weak var mySegmentedControl: UISegmentedControl!
和mySegmentedControl.selectedSegmentIndex = -1
使用Swift以编程方式取消选择UISegmentedControl。至于检测段的触摸,我不知道。希望其他人能得到答案。