在已选择的段上点击时检测事件 [英] detect event when tapped on already selected segment

查看:84
本文介绍了在已选择的段上点击时检测事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在触摸已选择的片段时获取事件.

Hi i want to get event when i touch on already selected segment.

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

i have implemented below solution

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事件将执行两次.

this works fine but ValueChanged event gets executed twice if i am tapping on non selected segment.

执行轻击手势不起作用.表示当我点击未选中的片段时,使用点击手势时会显示旧的选中片段.

Implementing tap gesture is not working. means when i tap on non selected segment it shows old selected segment when used tap gesture.

如果有解决方案,请提出建议.

If any solution please suggest.

推荐答案

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

I realize this is an older question, but I ran across the same problem where I needed to detect if the existing segment was selected as well as the selected segment changing.

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

The solution above was close, but here is what worked for me. Capture the existing, selected segment index on touchesBegan and then in touchesEnded, compare the old value to the current selected segment index. If they are the same, I manually trigger the .ValueChanged event. Note: this is Swift 2.0 syntax.

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 )
        }
    }
}

这篇关于在已选择的段上点击时检测事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆