我试图在Swift 3中实现长按,但它会被终止

时间:2017-03-10 15:33:33

标签: ios swift uigesturerecognizer

我想使用Swift 3为UIView创建一个长手势点击。我已经做了以下但问题是当我开始点击我的应用程序被终止。知道为什么吗?

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var image: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
      let longGesture = UILongPressGestureRecognizer(target: self, action: Selector("longTap:"))
        image.addGestureRecognizer(longGesture)
    }

    func longTap(sender : UIGestureRecognizer){
        print("Long tap")
        if sender.state == .ended {
            image.backgroundColor = UIColor.green

        }
        else if sender.state == .began {
            image.backgroundColor = UIColor.red
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您不应再使用Selector("longTap:")语法。而是使用#selector(ViewController.longTap)。问题是在重命名后,选择器不再被命名为您希望它命名的内容。尝试在游乐场中运行以下内容:

class Test : NSObject {
    func didLongTap1(sender : UIGestureRecognizer) {
    }
    func didLongTap2(_ sender : Any) {
    }
}

print("\(#selector(Test.didLongTap1))")
print("\(#selector(Test.didLongTap2))")
print("\(Selector("didLongTap1:"))")

打印:

didLongTap1WithSender:
didLongTap2:
didLongTap1: