我有一个UIView并且我添加了点击手势

let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
tap.delegate = self
myView.addGesture(tap)

我试图在testfile中以编程方式调用它。

sendActionForEvent

我正在使用这个函数,但它不起作用:

myView.sendActionForEvent(UIEvents.touchUpDown)

它显示未识别的选择器发送到实例。

我该如何解决这个问题呢?


当前回答

你需要用目标和动作初始化UITapGestureRecognizer,如下所示:

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
myView.addGestureRecognizer(tap)

然后,你应该实现处理程序,它将在每次tap事件发生时被调用:

@objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
    // handling code
}

所以现在调用你的点击手势识别器事件处理程序就像调用一个方法一样简单:

handleTap()

其他回答

我想指出两点,这两点一直给我带来麻烦。

I was creating the Gesture Recognizer on init and storing it in a let property. Apparently, adding this gesture recog to the view does not work. May be self object passed to the gesture recognizer during init, is not properly configured. The gesture recognizer should not be added to views with zero frames. I create all my views with zero frame and then resize them using autolayout. The gesture recognizers have to be added AFTER the views have been resized by the autolayout engine. So I add the gesture recognizer in viewDidAppear and they work.

我是在swift上的Xcode 6.4上完成的。见下文。

var view1: UIView!

func assignTapToView1() {          
  let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
  //  tap.delegate = self
  view1.addGestureRecognizer(tap)
  self.view .addSubview(view1)

...
}

func handleTap() {
 print("tap working")
 view1.removeFromSuperview()
 // view1.alpha = 0.1
}
    let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
    frontView.addGestureRecognizer(tap)

// Make sure this is not private
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
    print("tap working")
}

Swift 4的完整答案

步骤1:为视图创建一个出口

@IBOutlet weak var rightViewOutlet: UIView!

步骤2:定义一个点击手势

var tapGesture = UITapGestureRecognizer()

步骤3:创建ObjC函数(当视图被点击时调用)

@objc func rightViewTapped(_ recognizer: UIGestureRecognizer) {
    print("Right button is tapped")
}

步骤4:在viewDidLoad()中添加以下内容

let rightTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.rightViewTapped(_:)))
    rightViewOutlet.addGestureRecognizer(rightTap)

实现轻触手势

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "touchHappen") 
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)

当点击被识别时调用此函数。

func touchHappen() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    self.view.endEditing(true)
}

针对Swift 3 +的更新

let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchHappen(_:)))
yourView.addGestureRecognizer(tap)
yourView.userInteractionEnabled = true

func touchHappen(_ sender: UITapGestureRecognizer) {
    print("Hello Dear you are here")
}