我有以下问题:
在我的 viewDidLoad() 中,我有这段代码:
self.singleTapVar.numberOfTapsRequired = 1
self.singleTapVar.addTarget(self, action: #selector(ViewController.singleTapFunc))
self.touchUpRect.isUserInteractionEnabled = true
self.touchUpRect.addGestureRecognizer(self.singleTapVar)
我想为多个 View 调用它,所以我编写了函数:
func addTapToView(tap: UITapGestureRecognizer, view: UIView, method: Void, numberOfTaps: Int){
tap.numberOfTapsRequired = numberOfTaps
tap.addTarget(self, action: #selector(ViewController.method))
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tap)
}
然后在我的覆盖函数中调用这个函数:
addTapToView(tap: singleTapVar, view: touchUpRect, method: singleTapFunc(), numberOfTaps: 1)
问题是,当代码嵌入到一个函数中然后在覆盖函数中调用时,它会在我的应用程序第一次启动时自动执行并且点击按钮,这不会如果它正常编码就会发生,它不应该发生......
在此先致谢并致以最诚挚的问候 法比
最佳答案
您不是将选择器传递给函数,而是调用它并将结果传递给函数。
您应该更改您的函数以采用 Selector
而不是 Void
:
func addTapToView(tap: UITapGestureRecognizer, view: UIView, method: Selector, numberOfTaps: Int){
tap.numberOfTapsRequired = numberOfTaps
tap.addTarget(self, action: method)
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tap)
}
然后在调用函数时传递选择器:
addTapToView(tap: singleTapVar, view: touchUpRect, method: #selector(ViewController.singleTapFunc), numberOfTaps: 1)
关于ios - 添加UIGesture的函数自动执行override函数中的button方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46978790/