Why my #selector is not working?

Viewed 79

I have a function:

 @objc func handleLongPress(data: SkelbimasModel, _ gestureRecognizer:UIGestureRecognizer){
    if gestureRecognizer.state != .began{
        return
    }

    let touchPoint:CGPoint = gestureRecognizer.location(in: self.Map)
    let touchMapCoordinate:CLLocationCoordinate2D =
        self.Map.convert(touchPoint, toCoordinateFrom: self.Map)

    let annot:MKPointAnnotation = MKPointAnnotation()
    annot.coordinate = touchMapCoordinate

    self.resetTracking()
    self.Map.addAnnotation(annot)
    skelbimai.append(annot)
    print(skelbimai)
    self.Map.removeGestureRecognizer(gestureRecognizer)
    Label.isHidden = true
}

My SkelbimbasModel inherits NSObject :

class SkelbimasModel: NSObject {...}

And that function is not being called :

func addLongPressGesture(){
    let longPressRecogniser:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target:self , action:#selector(ViewController.handleLongPress(data:_:)))
    longPressRecogniser.minimumPressDuration = 0.5 //user needs to press for 1 seconds
    self.Map.addGestureRecognizer(longPressRecogniser)
}

When i remove SkelbimasModel property from function like :

@objc func handleLongPress(_ gestureRecognizer:UIGestureRecognizer)

works fine. How to declare function to selector, to pass SkalbimasModel property?

2 Answers

Selector signature must be one of the following.

@IBAction func myActionMethod()
@IBAction func myActionMethod(_ sender: UIGestureRecognizer)

Official Documentation

A gesture recognizer has one or more target-action pairs associated with it. If there are multiple target-action pairs, they are discrete, and not cumulative. Recognition of a gesture results in the dispatch of an action message to a target for each of the associated pairs. The action methods invoked must conform to one of the following signatures:

@IBAction func myActionMethod()

@IBAction func myActionMethod(_ sender: UIGestureRecognizer)

You can look into view tags if you wan't to differentiate between views.

let tag = gestureRecognizer.view?.tag

Here is an answer to your question: UIGestureRecognizer

UIGestureRecognizer action methods invoked must conform to one of the following signatures:

@IBAction func myActionMethod() 
// or func myActionMethod()

@IBAction func myActionMethod(_ sender: UIGestureRecognizer)
// or func myActionMethod(_ sender: UIGestureRecognizer)

You can pass an instance of UIGestureRecognizer only

Related