Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a function to a #selector

Tags:

swift

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?

like image 855
patrickS Avatar asked May 04 '16 08:05

patrickS


1 Answers

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

}

like image 129
Earl Grey Avatar answered Sep 19 '22 21:09

Earl Grey