在tapGesture动作选择器中包含协议功能 - iOS Swift

时间:2016-03-16 01:25:55

标签: ios swift selector uitapgesturerecognizer

我有一个类(FilterBar.swift)和一个viewcontroller。 viewcontroller调用类来填充带有图像列表的scrollView对象,每个图像都添加了一个tapGestureRecognizer,如下所示:

        let tapGesture = UITapGestureRecognizer(
                        target: imgView, action: Selector("filterClicked:"));
        tapGesture.numberOfTapsRequired = 1;
        tapGesture.numberOfTouchesRequired = 1;
        imgView.addGestureRecognizer(tapGesture);

我在FilterBar中也有一个函数,如下所示:

    @objc func filterClicked(sender: UITapGestureRecognizer) {
    print(sender.view?.superview?.description)
    print("sent from view: \(sender.view!.tag)");
}

当我尝试点击图片时,我收到以下错误:

2016-03-16 02:06:45.800 ImageFilter[71811:6885004] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView delegate.filterClicked:]: unrecognized selector sent to instance 0x7fc07951f010'

所以我想也许我需要一个协议,所以我在FilterBar中创建了一个协议如下:

protocol FilterClickedDelegate {
    func filterClicked(sender: UITapGestureRecognizer);
}

let delegate:FilterClickedDelegate?

(adjusted this line) let tapGesture = UITapGestureRecognizer(
             target: imgView, action: Selector("delegate.filterClicked:"));

我将该协议添加到viewcontroller类,我还添加了协议所需的功能,但我仍然得到相同的错误。所以第一个问题:我是否正确使用此Senario中的协议,因为它在viewcontroller上运行?

第二个问题:我在选择器中做错了什么?是否有一种特定的方式来提及选择器中的协议功能?

2 个答案:

答案 0 :(得分:1)

邮政编码的最后一行:

(adjusted this line) let tapGesture = UITapGestureRecognizer(
             target: imgView, action: Selector("delegate.filterClicked:"));  

我认为应该是:

(adjusted this line) let tapGesture = UITapGestureRecognizer(
         target: delegate, action: Selector("filterClicked:"));  

我认为它会起作用。
但我并不建议以这种方式做,这有点奇怪。我通常做的是:

(adjusted this line) let tapGesture = UITapGestureRecognizer(
         target: self, action: Selector("filterClicked:"));   

如果我真的需要通知delegate做某事,我会致电delegatefilterClicked:进行操作。就像:

在ViewController中:

fun filterClicked() {
// delegate to do something
delegate.xxx()
}

答案 1 :(得分:0)

我想通了,在初始化UITapGestureRecognizer的目标部分中,您需要使用viewcontroller,它实际上是委托者的委托。这样:

let tapGesture = UITapGestureController(target: vc, action:"filterClicked:");

谢谢大家,并希望这会帮助其他人坚持同样的问题!

喝彩!