如何用swift编程调用UIView上的手势点击

时间:2022-09-06 21:09:36

I have a UIView and and I have added tap gesture to it:

我有一个UIView,我添加了tap手势

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

I am trying to call it programmatically in the testfile.

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

sendActionForEvent

I am using this function, but it is not working:

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

myView.sendActionForEvent(UIEvents.touchUpDown)

It shows unrecognised selector sent to instance.

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

How can I solve this problem?

我如何解决这个问题?

Thanks in advance

谢谢提前

17 个解决方案

#1


112  

You need to initialize UITapGestureRecognizer with a target and action, like so:

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

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
tap.delegate = self // This is not required
myView.addGestureRecognizer(tap)

Then, you should implement the handler, which will be called each time when a tap event occurs:

然后,您应该实现处理程序,每次发生tap事件时都会调用该处理程序:

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

So now calling your tap gesture recognizer event handler is as easy as calling a method:

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

handleTap()

#2


69  

For anyone who is looking for Swift 3 solution

对于任何正在寻找Swift 3解决方案的人来说

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

view.addGestureRecognizer(tap)

view.isUserInteractionEnabled = true

self.view.addSubview(view)

// function which is triggered when handleTap is called
 func handleTap(_ sender: UITapGestureRecognizer) {
     print("Hello World")
  }

#3


41  

Just a note - Don't forget to enabled interaction on the view:

请注意——不要忘记在视图上启用交互:

let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))

view.addGestureRecognizer(tap)

// view.userInteractionEnabled = true

self.view.addSubview(view)

#4


30  

For Swift 4:

为迅速4:

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

view.addGestureRecognizer(tap)

view.isUserInteractionEnabled = true

self.view.addSubview(view)

// function which is triggered when handleTap is called
@objc func handleTap(_ sender: UITapGestureRecognizer) {
    print("Hello World")
}

In Swift 4, you need to explicitly indicate that the triggered function is callable from Objective-C, so you need to add @objc too your handleTap function.

在Swift 4中,您需要显式地表明,触发函数可以从Objective-C调用,因此您需要添加@objc以及handleTap函数。

See @Ali Beadle 's answer here: Swift 4 add gesture: override vs @objc

见@Ali Beadle的回答:Swift 4添加手势:override vs @objc

#5


12  

SWIFT 3.0 UITapGesture

斯威夫特3.0 UITapGesture

STEP : 1

步骤:1

@IBOutlet var viewTap: UIView!

STEP : 2

一步:2

var tapGesture = UITapGestureRecognizer()

STEP : 3

一步:3

override func viewDidLoad() {
    super.viewDidLoad()
    // TAP Gesture
    tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.myviewTapped(_:)))
    tapGesture.numberOfTapsRequired = 1
    tapGesture.numberOfTouchesRequired = 1
    viewTap.addGestureRecognizer(tapGesture)
    viewTap.isUserInteractionEnabled = true
}

STEP : 4

一步:4

func myviewTapped(_ sender: UITapGestureRecognizer) {

    if self.viewTap.backgroundColor == UIColor.yellow {
        self.viewTap.backgroundColor = UIColor.green
    }else{
        self.viewTap.backgroundColor = UIColor.yellow
    }
}

OUTPUT

输出

如何用swift编程调用UIView上的手势点击

#6


9  

Implementing tap gesture

实现点击手势

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

Calls this function when the tap is recognized.

在确认tap时调用此函数。

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

Update for For Swift 3

Swift 3更新

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

func touchHappen(_ sender: UITapGestureRecognizer) {
    print("Hello Museer")
}

#7


7  

This is how it works in Swift 3:

这就是《Swift 3》的运作方式:

@IBOutlet var myView: UIView!
override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action:#selector(handleTap))

    myView.addGestureRecognizer(tap)
}

func handleTap() {
    print("tapped")
}

#8


6  

I worked out on Xcode 6.4 on swift. See below.

我在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
}

#9


5  

You need to initialize UITapGestureRecognizer with a target and action, like so:

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

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

Then, you should implement the handler, which will be called each time when a tap event occurs:

然后,您应该实现处理程序,每次发生tap事件时都会调用该处理程序:

func handleTap(sender: UITapGestureRecognizer) {
  // handling code
}

#10


4  

Swift 4

斯威夫特4

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

@objc func touchTapped(_ sender: UITapGestureRecognizer) {
}

#11


3  

    let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
    frontView.addGestureRecognizer(tap)

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

#12


2  

If you want Objective C code is given below,

如果您想要目标C代码如下所示,

UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; // Declare the Gesture.
gesRecognizer.delegate = self;
[yourView addGestureRecognizer:gesRecognizer]; // Add Gesture to your view.

// Declare the Gesture Recognizer handler method.

- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
   NSLog(@"Tapped");
}

or you want swift code is given below,

或者您希望swift代码如下,

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add tap gesture recognizer to view
        let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        myView.addGestureRecognizer(tapGesture)
    }

    // this method is called when a tap is recognized
    func handleTap(sender: UITapGestureRecognizer) {

        print("tap")
    }
}

#13


1  

Try the following swift code (tested in Xcode 6.3.1):

尝试以下swift代码(Xcode 6.3.1测试):

    import UIKit

    class KEUITapGesture150427 : UIViewController {
      var _myTap: UITapGestureRecognizer?
      var _myView: UIView?

      override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor();

        _myTap = UITapGestureRecognizer(target: self
, action: Selector("_myHandleTap:"))
        _myTap!.numberOfTapsRequired = 1

        _myView = UIView(frame: CGRectMake(100, 200, 100, 100))
        _myView!.backgroundColor=UIColor.blueColor()
        _myView!.layer.cornerRadius = 20
        _myView!.layer.borderWidth = 1
        _myView!.addGestureRecognizer(_myTap!)
        view.addSubview(_myView!)
      }

      func _myHandleTap(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
          println("_myHandleTap(sender.state == .Ended)")
          sender.view!.backgroundColor
          = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0);
        }
      }
    }

Note that your target could be any subclass of UIResponder, see (tested in Xcode 6.3.1):

注意,您的目标可以是UIResponder的任何子类,参见(在Xcode 6.3.1中测试):

    import UIKit

    class MyTapTarget  : UIResponder {
      func _myHandleTap2(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
          println("_myHandleTap2(sender.state == .Ended)")
          sender.view!.backgroundColor
            = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0);
        }
      }
    }

    class KEUITapGesture150427b : UIViewController {
      var _myTap: UITapGestureRecognizer?
      var _myView: UIView?
      var _myTapTarget: MyTapTarget?

      override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor();

        _myTapTarget = MyTapTarget()
        _myTap = UITapGestureRecognizer(target: _myTapTarget!
, action: Selector("_myHandleTap2:"))
        _myTap!.numberOfTapsRequired = 1

        _myView = UIView(frame: CGRectMake(100, 200, 100, 100))
        _myView!.backgroundColor=UIColor.blueColor()
        _myView!.layer.cornerRadius = 20
        _myView!.layer.borderWidth = 1
        _myView!.addGestureRecognizer(_myTap!)
        view.addSubview(_myView!)
      }
    }

#14


1  

I worked out on Xcode 7.3.1 on Swift 2.2. See below.

我在Swift 2.2上设计了Xcode 7.3.1。见下文。

func addTapGesture() {
    let tap = UITapGestureRecognizer(target: self, action: #selector(MyViewController.handleTap))
    tap.numberOfTapsRequired = 1
    self.myView.addGestureRecognizer(tap)
}

func handleTap() {
    // Your code here...
}

#15


0  

Instead of invoking myView's UITapGestureRecognizer, you can directly call the handleTap function,

不调用myView的UITapGestureRecognizer,你可以直接调用handleTap函数,

#16


0  

I wanted to specify two points which kept causing me problems.

我想指出两点,这两点一直困扰着我。

  • 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.
  • 我在init中创建了手势识别器并将其存储在let属性中。显然,向视图添加这个手势recog是行不通的。可能是在初始化过程中传递给手势识别器的self对象,没有正确配置。
  • 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.
  • 手势识别器不应该添加到零帧的视图中。我用零帧创建所有视图,然后使用autolayout调整它们的大小。在视图被自动布局引擎调整大小之后,必须添加手势识别器。我在viewDidAppear中添加了手势识别器,它们可以工作。

#17


0  

xCode 9.3, Swift 4.0

xCode 9.3,4.0迅速

class BaseVC: UIViewController, UIGestureRecognizerDelegate { 

      @IBOutlet weak var iView: UIView!

      override func viewDidLoad() {
          super.viewDidLoad()
          let clickUITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onSelect(_:)))
          clickUITapGestureRecognizer.delegate = self
          iView?.addGestureRecognizer(tap)
      }

      func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
          return true
      }


     @IBAction func onSelect(_ sender: Any) {

     }
}

#1


112  

You need to initialize UITapGestureRecognizer with a target and action, like so:

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

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
tap.delegate = self // This is not required
myView.addGestureRecognizer(tap)

Then, you should implement the handler, which will be called each time when a tap event occurs:

然后,您应该实现处理程序,每次发生tap事件时都会调用该处理程序:

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

So now calling your tap gesture recognizer event handler is as easy as calling a method:

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

handleTap()

#2


69  

For anyone who is looking for Swift 3 solution

对于任何正在寻找Swift 3解决方案的人来说

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

view.addGestureRecognizer(tap)

view.isUserInteractionEnabled = true

self.view.addSubview(view)

// function which is triggered when handleTap is called
 func handleTap(_ sender: UITapGestureRecognizer) {
     print("Hello World")
  }

#3


41  

Just a note - Don't forget to enabled interaction on the view:

请注意——不要忘记在视图上启用交互:

let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))

view.addGestureRecognizer(tap)

// view.userInteractionEnabled = true

self.view.addSubview(view)

#4


30  

For Swift 4:

为迅速4:

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

view.addGestureRecognizer(tap)

view.isUserInteractionEnabled = true

self.view.addSubview(view)

// function which is triggered when handleTap is called
@objc func handleTap(_ sender: UITapGestureRecognizer) {
    print("Hello World")
}

In Swift 4, you need to explicitly indicate that the triggered function is callable from Objective-C, so you need to add @objc too your handleTap function.

在Swift 4中,您需要显式地表明,触发函数可以从Objective-C调用,因此您需要添加@objc以及handleTap函数。

See @Ali Beadle 's answer here: Swift 4 add gesture: override vs @objc

见@Ali Beadle的回答:Swift 4添加手势:override vs @objc

#5


12  

SWIFT 3.0 UITapGesture

斯威夫特3.0 UITapGesture

STEP : 1

步骤:1

@IBOutlet var viewTap: UIView!

STEP : 2

一步:2

var tapGesture = UITapGestureRecognizer()

STEP : 3

一步:3

override func viewDidLoad() {
    super.viewDidLoad()
    // TAP Gesture
    tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.myviewTapped(_:)))
    tapGesture.numberOfTapsRequired = 1
    tapGesture.numberOfTouchesRequired = 1
    viewTap.addGestureRecognizer(tapGesture)
    viewTap.isUserInteractionEnabled = true
}

STEP : 4

一步:4

func myviewTapped(_ sender: UITapGestureRecognizer) {

    if self.viewTap.backgroundColor == UIColor.yellow {
        self.viewTap.backgroundColor = UIColor.green
    }else{
        self.viewTap.backgroundColor = UIColor.yellow
    }
}

OUTPUT

输出

如何用swift编程调用UIView上的手势点击

#6


9  

Implementing tap gesture

实现点击手势

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

Calls this function when the tap is recognized.

在确认tap时调用此函数。

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

Update for For Swift 3

Swift 3更新

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

func touchHappen(_ sender: UITapGestureRecognizer) {
    print("Hello Museer")
}

#7


7  

This is how it works in Swift 3:

这就是《Swift 3》的运作方式:

@IBOutlet var myView: UIView!
override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action:#selector(handleTap))

    myView.addGestureRecognizer(tap)
}

func handleTap() {
    print("tapped")
}

#8


6  

I worked out on Xcode 6.4 on swift. See below.

我在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
}

#9


5  

You need to initialize UITapGestureRecognizer with a target and action, like so:

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

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

Then, you should implement the handler, which will be called each time when a tap event occurs:

然后,您应该实现处理程序,每次发生tap事件时都会调用该处理程序:

func handleTap(sender: UITapGestureRecognizer) {
  // handling code
}

#10


4  

Swift 4

斯威夫特4

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

@objc func touchTapped(_ sender: UITapGestureRecognizer) {
}

#11


3  

    let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
    frontView.addGestureRecognizer(tap)

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

#12


2  

If you want Objective C code is given below,

如果您想要目标C代码如下所示,

UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; // Declare the Gesture.
gesRecognizer.delegate = self;
[yourView addGestureRecognizer:gesRecognizer]; // Add Gesture to your view.

// Declare the Gesture Recognizer handler method.

- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
   NSLog(@"Tapped");
}

or you want swift code is given below,

或者您希望swift代码如下,

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add tap gesture recognizer to view
        let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        myView.addGestureRecognizer(tapGesture)
    }

    // this method is called when a tap is recognized
    func handleTap(sender: UITapGestureRecognizer) {

        print("tap")
    }
}

#13


1  

Try the following swift code (tested in Xcode 6.3.1):

尝试以下swift代码(Xcode 6.3.1测试):

    import UIKit

    class KEUITapGesture150427 : UIViewController {
      var _myTap: UITapGestureRecognizer?
      var _myView: UIView?

      override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor();

        _myTap = UITapGestureRecognizer(target: self
, action: Selector("_myHandleTap:"))
        _myTap!.numberOfTapsRequired = 1

        _myView = UIView(frame: CGRectMake(100, 200, 100, 100))
        _myView!.backgroundColor=UIColor.blueColor()
        _myView!.layer.cornerRadius = 20
        _myView!.layer.borderWidth = 1
        _myView!.addGestureRecognizer(_myTap!)
        view.addSubview(_myView!)
      }

      func _myHandleTap(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
          println("_myHandleTap(sender.state == .Ended)")
          sender.view!.backgroundColor
          = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0);
        }
      }
    }

Note that your target could be any subclass of UIResponder, see (tested in Xcode 6.3.1):

注意,您的目标可以是UIResponder的任何子类,参见(在Xcode 6.3.1中测试):

    import UIKit

    class MyTapTarget  : UIResponder {
      func _myHandleTap2(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
          println("_myHandleTap2(sender.state == .Ended)")
          sender.view!.backgroundColor
            = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0);
        }
      }
    }

    class KEUITapGesture150427b : UIViewController {
      var _myTap: UITapGestureRecognizer?
      var _myView: UIView?
      var _myTapTarget: MyTapTarget?

      override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor();

        _myTapTarget = MyTapTarget()
        _myTap = UITapGestureRecognizer(target: _myTapTarget!
, action: Selector("_myHandleTap2:"))
        _myTap!.numberOfTapsRequired = 1

        _myView = UIView(frame: CGRectMake(100, 200, 100, 100))
        _myView!.backgroundColor=UIColor.blueColor()
        _myView!.layer.cornerRadius = 20
        _myView!.layer.borderWidth = 1
        _myView!.addGestureRecognizer(_myTap!)
        view.addSubview(_myView!)
      }
    }

#14


1  

I worked out on Xcode 7.3.1 on Swift 2.2. See below.

我在Swift 2.2上设计了Xcode 7.3.1。见下文。

func addTapGesture() {
    let tap = UITapGestureRecognizer(target: self, action: #selector(MyViewController.handleTap))
    tap.numberOfTapsRequired = 1
    self.myView.addGestureRecognizer(tap)
}

func handleTap() {
    // Your code here...
}

#15


0  

Instead of invoking myView's UITapGestureRecognizer, you can directly call the handleTap function,

不调用myView的UITapGestureRecognizer,你可以直接调用handleTap函数,

#16


0  

I wanted to specify two points which kept causing me problems.

我想指出两点,这两点一直困扰着我。

  • 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.
  • 我在init中创建了手势识别器并将其存储在let属性中。显然,向视图添加这个手势recog是行不通的。可能是在初始化过程中传递给手势识别器的self对象,没有正确配置。
  • 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.
  • 手势识别器不应该添加到零帧的视图中。我用零帧创建所有视图,然后使用autolayout调整它们的大小。在视图被自动布局引擎调整大小之后,必须添加手势识别器。我在viewDidAppear中添加了手势识别器,它们可以工作。

#17


0  

xCode 9.3, Swift 4.0

xCode 9.3,4.0迅速

class BaseVC: UIViewController, UIGestureRecognizerDelegate { 

      @IBOutlet weak var iView: UIView!

      override func viewDidLoad() {
          super.viewDidLoad()
          let clickUITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onSelect(_:)))
          clickUITapGestureRecognizer.delegate = self
          iView?.addGestureRecognizer(tap)
      }

      func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
          return true
      }


     @IBAction func onSelect(_ sender: Any) {

     }
}