【问题标题】:detect event when tapped on already selected segment点击已选择的片段时检测事件
【发布时间】:2015-07-26 02:08:30
【问题描述】:

嗨,当我触摸已选择的片段时,我想获得事件。

我已经实现了以下解决方案

import UIKit

class MARSSegmentController: UISegmentedControl {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
    // Drawing code
    }
    */

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        let oldValue:NSInteger = self.selectedSegmentIndex
        super.touchesBegan(touches, withEvent: event)
        if oldValue == self.selectedSegmentIndex{
            sendActionsForControlEvents(UIControlEvents.ValueChanged)
        }
    }    
} 

这工作正常,但如果我点击非选定段,ValueChanged 事件会执行两次。

实现点击手势不起作用。意味着当我点击非选定段时,它会在使用点击手势时显示旧的选定段。

如果有任何解决方案,请提出建议。

【问题讨论】:

  • 如果我错了,请原谅我,但我认为这会在触地和触地时运行。
  • 您可以先检查 UIEvent 的值类型是否已更改,然后不要调用此 sendActionsForControlEvents(UIControlEvents.ValueChanged)

标签: ios swift uisegmentedcontrol


【解决方案1】:

只放self.nameSegmentedControl.isMomentary = true

通过与 valueChanges 关联的方法,检测到点击。

【讨论】:

  • 最糟糕的解决方案!
【解决方案2】:

我意识到这是一个较老的问题,但我遇到了同样的问题,我需要检测是否选择了现有细分以及所选细分是否发生变化。

上面的解决方案很接近,但这对我有用。在 touchesBegan 上捕获现有的选定段索引,然后在 touchesEnded 中,将旧值与当前选定的段索引进行比较。如果它们相同,我手动触发 .ValueChanged 事件。注意:这是 Swift 2.0 的语法。

class SegmentedControlExistingSegmentTapped : UISegmentedControl
{
    // captures existing selected segment on touchesBegan
    var oldValue : Int!

    override func touchesBegan( touches: Set<UITouch>, withEvent event: UIEvent? )
    {
        self.oldValue = self.selectedSegmentIndex
        super.touchesBegan( touches , withEvent: event )
    }

    // This was the key to make it work as expected
    override func touchesEnded( touches: Set<UITouch>, withEvent event: UIEvent? )
    {
        super.touchesEnded( touches , withEvent: event )

        if self.oldValue == self.selectedSegmentIndex
        {
            sendActionsForControlEvents( .ValueChanged )
        }
    }
}

【讨论】:

    【解决方案3】:

    我认为您的问题在于if oldValue == self.selectedSegmentIndex 将始终返回true,因为let oldValue:NSInteger = self.selectedSegmentIndex。因此,您只需使用 if oldValue == selectedValue 更改您的 if 条件,其中 selectedValue 是您认为已选择细分的值

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多