简体   繁体   中英

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?

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")

}

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.

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")

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM