Epic Gamer_1
Epic Gamer_1

Reputation: 114

Swift 2.2 - Value of type ViewController has no member action

I have been getting the error "Value of type 'ViewController' has no member 'action'"

(action being the function)

Here is the code I am using for the function and Gesture Recogniser

   let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(self.action))

    uilpgr.minimumPressDuration = 2

    Map.addGestureRecognizer(uilpgr)

    func action(gestureRecogniser: UIGestureRecognizer) {

        print("Gesture Recognised")


    }

let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(self.action))

This is where the error occurs at self.action

What am I doing wrong and how do I fix it?

Upvotes: 1

Views: 4804

Answers (3)

Richard So
Richard So

Reputation: 33

the accepted Blake Lockley's answer was right before Swift 4; however in Swift 4, the code need to be changed to the following in order to be compiled correctly (add the @objc marker to the target function):

override func viewDidLoad() {

  super.viewDidLoad()

  let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.action))
}

@objc func action(gesture:UIGestureRecognizer){

  print("receives gesture")

}

Upvotes: 2

SagarS
SagarS

Reputation: 21

This is working on Xcode 8:

override func viewDidLoad() {

  super.viewDidLoad()

  let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.action))
}

func action(gesture:UIGestureRecognizer){

  print("receives gesture")

}

Upvotes: 1

Blake Lockley
Blake Lockley

Reputation: 2961

Your method action is declared locally within the same method that is creating the gesture recognizer.

To resolve this move your action method outside of the method it is currently in. So that is is its own method of the class ViewController and not inside any other functions.

Upvotes: 1

Related Questions