Question

UILongPressGestureRecognizer got added to UISegmentedControl. Is there a way to detect selectedSegmentIndex when long-pressing down? thanks, in advance.

Was it helpful?

Solution

Did you try adding a UILongPressGestureRecognizer to it? In viewDidLoad:

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
longPress.delegate = self;
[segmentedControl addGestureRecognizer:longPress];

Don't forget to add UIGestureRecognizerDelegate to your header file.

To know where is pressed:

- (void)longPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    CGPoint p = [gestureRecognizer locationInView:segmentedControl];
}

Then you could check what segment of segmentedControl matches with CGPoint p, check for the Y-coordinate, for example. When it's left from the middle line of the UISegmentedControl it's segment 0, when it's right of that line it's segment 1.

OTHER TIPS

You register for long press in UISegmentedControl

  let longPress = UILongPressGestureRecognizer(target: self, action: #selector(ListQuizViewController.segmentLongPress(_:)))
    //longPress.delegate = self;
    self.segmentedControl.addGestureRecognizer(longPress)
    longPress.minimumPressDuration = 1

You get index of selected button as follows with the assumption that segments are equally spaced

 func segmentLongPress(gestureRecognizer:UILongPressGestureRecognizer)
    {
        let p = gestureRecognizer.locationInView(self.segmentedControl)
        let index = Int(ceil( p.x/(self.segmentedControl.frame.width/4))) - 1
       self.segmentedControl.selectedSegmentIndex = index

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top