patrickS
patrickS

Reputation: 3760

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?

Upvotes: 8

Views: 2851

Answers (2)

Earl Grey
Earl Grey

Reputation: 7466

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

}

Upvotes: 11

Himanshu
Himanshu

Reputation: 2832

It's not possible, rather you can call your desired function from the return of the first function whose data you want to pass to the other one. And your scenario may change according to your requirement.

Upvotes: 0

Related Questions