添加UIGesture的功能自动执行覆盖功能中的按钮方法

时间:2017-10-27 15:39:42

标签: ios swift xcode override

我有以下问题:

在我的viewDidLoad()中,我有这段代码:

    self.singleTapVar.numberOfTapsRequired = 1
    self.singleTapVar.addTarget(self, action: #selector(ViewController.singleTapFunc))
    self.touchUpRect.isUserInteractionEnabled = true
    self.touchUpRect.addGestureRecognizer(self.singleTapVar)

我想为多个视图调用它,所以我编写了函数:

    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)

问题是,当代码嵌入到函数中然后在覆盖函数中调用时,它会在我的应用程序首次启动时自动执行,并且按下按钮,这不会如果它正常编码而且不应该发生......

提前致谢并致以最诚挚的问候 FABI

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

调用此方法时,在点击视图之前调用singleTapFunc()

addTapToView(tap: singleTapVar, view: touchUpRect, method: singleTapFunc(), numberOfTaps: 1)

删除它,并在addTapToView(:,:,:)方法中调用singleTapFunc()

func addTapToView(tap: UITapGestureRecognizer, view: UIView, numberOfTaps: Int){
        tap.numberOfTapsRequired = numberOfTaps
        tap.addTarget(self, action: #selector(self.singleTapFunc))
        view.isUserInteractionEnabled = true
        view.addGestureRecognizer(tap)
    }