iosswiftlong-pressswift4.1uilongpressgesturerecogni

Long Press Gesture called multiple times


I am getting an issue with UILongPressGestureRecognizer, I have used this code:-

func addLongPressGesture(){
        let lngPr = UILongPressGestureRecognizer.init(target: self, action: #selector(self.handleLongPress(gesture:)))
        lngPr.delaysTouchesEnded = true
        self.addGestureRecognizer(lngPr)
    }
    @objc func handleLongPress(gesture:UIGestureRecognizer){
       
        if selectedIndexPath != nil && delegate != nil{
            self.delegate?.delegateLongPressed(atIndexPath: selectedIndexPath!)
        }
    }

Solution

  • Hey you need to check the state of UILongPressGesture to reform your functions Try this :-

    func addLongPressGesture(){
            let lngPr = UILongPressGestureRecognizer.init(target: self, action: #selector(self.handleLongPress(gesture:)))
            lngPr.delaysTouchesEnded = true
            self.addGestureRecognizer(lngPr)
        }
        @objc func handleLongPress(gesture:UIGestureRecognizer){
            if gesture.state == .ended{
            if selectedIndexPath != nil && delegate != nil{
                self.delegate?.delegateLongPressed(atIndexPath: selectedIndexPath!)
            }
            }
        }