ios - UISegmentedControl 再次按下取消选择段

标签 ios uisegmentedcontrol

如何通过再次按下同一段来取消选择 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/

相关文章:

ios - 如何在不同的iphone版本上显示不同的图片?

iOS 检查 JSON 返回是否有 Key

ios 使用 Storyboard 可本地化字符串进行动态本地化

objective-c - UISegmentedControl 以编程方式重置

iphone - 用于更改 View 的 UISegmented View

iOS facebook 登录响应不包含配置文件数据

ios - bundle ID 是否可以重复用于同一 iTunes Connect 帐户中的不同应用程序?

ios - UISegmentedControl外观无边框锐边

iphone - 如何在 iphone 应用程序开发中的导航栏上的分段 Controller 上添加下一个和上一个按钮?

ios - 带有 UISegmentedControl 的 UINavigationBar 部分覆盖了 childViews