问题
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.
回答1:
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 )
}
}
}
回答2:
I think your problem stands on the fact that if oldValue == self.selectedSegmentIndex
will always return true because of let oldValue:NSInteger = self.selectedSegmentIndex
. So all you need is to change your if condition with if oldValue == selectedValue
where selectedValue is value with which you consider segment selected
回答3:
Only putself.nameSegmentedControl.isMomentary = true
With your method associate to valueChanges, the tap is detected.
来源:https://stackoverflow.com/questions/30237667/detect-event-when-tapped-on-already-selected-segment