我得到一个函数作为函数参数,并希望在#selector中设置它。 但我收到错误消息:
Argument of '#selector' cannot refer to a property
我有以下功能:
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)
}
任何想法如何处理?
答案 0 :(得分:8)
这个怎么样?
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)
}
}
答案 1 :(得分:0)
这是不可能的,相反,您可以从第一个函数的返回调用您想要的函数,该函数的数据要传递给另一个函数。 您的情况可能会根据您的要求而改变。