UITapGestureRecognizer无法识别的选择器发送到实例

时间:2014-07-29 17:36:12

标签: ios swift selector uitapgesturerecognizer

我已经搜索过这个问题的解决方案,但在我的案例中找不到任何似乎可以解决的问题。我从UITapGestureRecognizer获得了上述异常。

以下是简化代码:

import UIKit;

class ViewController : UIViewController, UIScrollViewDelegate
{
    @IBOutlet weak var scrollView:UIScrollView!;
    var imageView:UIImageView!;

    override func viewDidLoad()
    {
        super.viewDidLoad();

        ... set up imageView/scrollView here ...

        let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "onScrollViewDoubleTapped");
        doubleTapRecognizer.numberOfTapsRequired = 2;
        doubleTapRecognizer.numberOfTouchesRequired = 1;
        scrollView.addGestureRecognizer(doubleTapRecognizer);
    }


    func onScrollViewDoubleTapped(recognizer:UITapGestureRecognizer)
    {
    }
}

有人能说出这段代码有什么问题吗?对我来说似乎都是正确的。我怀疑它与将ViewController指定为scrollView的委托(或反之亦然)有关?但是,ViewController被设置为scrollView的委托。但也许它会导致这个错误?

6 个答案:

答案 0 :(得分:22)

尝试在选择器字符串中添加冒号。

let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "onScrollViewDoubleTapped:");

正如cabellicar123所提到的,这表明选择器采用了参数。

答案 1 :(得分:4)

Swift 4使用#selector

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didSelectItem(sender:)))

@objc func didSelectItem(sender: AnyObject?) {
    print("didSelectItem: \(sender)")
}

答案 2 :(得分:2)

还可以尝试在方法中添加参数:

...(target: self, action: "yourMethodName:")

func yourMethodName(sender: AnyObject?)
{
    println("Clicked yourMethodName")
}

答案 3 :(得分:1)

也许可以帮助某人:我有这个错误,因为我声明了选择器方法的私有性:

func setup() {
  let singleFingerTap = UITapGestureRecognizer(target: self, action: "didTapOnViewInteraction:")
  singleFingerTap.numberOfTapsRequired = 1
  self.viewInteraction.addGestureRecognizer(singleFingerTap)
}

private func didTapOnViewInteraction(recognizer: UITapGestureRecognizer) {

}

删除"私人"关键字,一切都很棒!

答案 4 :(得分:1)

for swift 4

override func viewDidLoad() {
        super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(SignUpViewController.click))
    userImage.addGestureRecognizer(tap)
    userImage.isUserInteractionEnabled = true
}

@objc func click()
{
    print("Tapped on Image")
}

其中SignUpViewController是您的viewcontroller名称

答案 5 :(得分:0)

在我的情况下,使用Swift 4,选择器被正确定义,但由于带有手势的项目在集合视图中,因此导致无法找到选择器。我实现了一个自定义单元格并在其中配置了选择器

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "recent", for: indexPath) as! MyCollectionViewCell

cell.configureGestureWith(entry: recentEntries.sorted(by: {$0.createdAt > $1.createdAt})[indexPath.row], sender: self)

希望这对某人有所帮助。