问题描述
我有一个类 (FilterBar.swift) 和一个视图控制器.viewcontroller 调用该类以使用图像列表填充 scrollView 对象,并且每个图像都添加了一个 tapGestureRecognizer,如下所示:
I have a class (FilterBar.swift) and a viewcontroller. the viewcontroller calls the class to populate a scrollView object with list of images and each image has a tapGestureRecognizer added to it as follows:
let tapGesture = UITapGestureRecognizer(
target: imgView, action: Selector("filterClicked:"));
tapGesture.numberOfTapsRequired = 1;
tapGesture.numberOfTouchesRequired = 1;
imgView.addGestureRecognizer(tapGesture);
而且我在 FilterBar 中也有一个函数,如下所示:
and i have a function also in FilterBar as follows:
@objc func filterClicked(sender: UITapGestureRecognizer) {
print(sender.view?.superview?.description)
print("sent from view: \(sender.view!.tag)");
}
当我尝试单击图像时,出现以下错误:
when i attempt to click on the image i get the following error:
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 中创建了一个协议,如下所示:
So i thought maybe i need a protocol, so i created a protocol in FilterBar as follows:
protocol FilterClickedDelegate {
func filterClicked(sender: UITapGestureRecognizer);
}
let delegate:FilterClickedDelegate?
(adjusted this line) let tapGesture = UITapGestureRecognizer(
target: imgView, action: Selector("delegate.filterClicked:"));
我将该协议添加到 viewcontroller 类中,并且我还添加了协议所需的功能,但我仍然遇到相同的错误.所以第一个问题:我在这个场景中使用协议是否正确,因为它在视图控制器上运行?
i added that protocol to the viewcontroller class, and i also added the function the protocol needs but i still get the same error. So first question: Am i right to use a protocol in this senario since this is running on viewcontroller?
第二个问题:我在选择器中做错了什么?有没有具体的方法可以在选择器中提及协议函数?
second question: what am i doing wrong in the selector? is there a specific way to mention a protocol function in the selector?
推荐答案
我想通了,在目标部分初始化 UITapGestureRecognizer 时,您需要使用 viewcontroller,它实际上是委托人的委托.所以:
I figured it out, in the target section when initializing the UITapGestureRecognizer you need to use the viewcontroller which is actually the delegate of the delegator. so:
let tapGesture = UITapGestureController(target: vc, action:"filterClicked:");
谢谢大家,希望这能帮助其他陷入同一问题的人!
Thanks all, and hope this will help others stuck on the same issue!
干杯!
这篇关于在 tapGesture 操作选择器中包含协议功能 - iOS Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!