Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect event when tapped on already selected segment

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

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.

like image 572
Dattatray Deokar Avatar asked May 14 '15 12:05

Dattatray Deokar


1 Answers

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.

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 )
        }
    }
}
like image 54
Dan Nichols Avatar answered Nov 13 '22 08:11

Dan Nichols