patrickS patrickS - 7 months ago 19
Swift Question

Pass a function to a #selector

I get a function as function parameter and want to set this in a #selector.
But I get the error message:

Argument of '#selector' cannot refer to a property


I have the following function:

private func addGestureRecognizerToItem(selector: () -> ()) {
let labelGesture = UITapGestureRecognizer(target: self, action: #selector(selector))
let imageGesture = UITapGestureRecognizer(target: self, action: #selector(selector))
label.addGestureRecognizer(labelGesture)
imageView.addGestureRecognizer(imageGesture)
}


Any ideas how to handle this?

Answer

How about this?

class ViewController: UIViewController {

let label = UILabel()
let imageView = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()

    addGestureRecognizerToItem(#selector(test))
}

func test() {
}

private func addGestureRecognizerToItem(selector: Selector) {
    let labelGesture = UITapGestureRecognizer(target: self, action: selector)
    let imageGesture = UITapGestureRecognizer(target: self, action: selector)
    label.addGestureRecognizer(labelGesture)
    imageView.addGestureRecognizer(imageGesture)
}

}

Comments