如何以编程方式快速调用UIView上的手势点击


165

我有一个UIView,并向其中添加了点击手势:

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

我试图在测试文件中以编程方式调用它。

sendActionForEvent

我正在使用此功能,但无法正常工作:

myView.sendActionForEvent(UIEvents.touchUpDown)

它显示了无法识别的选择器发送到实例。

我怎么解决这个问题?


2
在SWIFT 2.2,你可以使用新的选择语法:让自来水= UITapGestureRecognizer(目标:自我,动作:#selector(self.handleTap(_ :)))
Wujo

@wujo-谢谢你;奇怪的是,它实际上对我不起作用,在UIView中也许仅在视图控制器中?
Fattie

2
另外,imageView.userInteractionEnabled = true如果您使用的是图像视图,请记住拥有。太久才发现它。
乔什

@Josh,是的,很重要。
NeverHopeless

1
@KhangAzun最好的选择是直接调用tap函数
George

Answers:


244

您需要UITapGestureRecognizer使用目标和操作进行初始化,如下所示:

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

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

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

因此,现在调用轻击手势识别器事件处理程序就像调用方法一样简单:

handleTap()

而不是直接调用选择器函数,我想通过编程调用UITapGestureRecognizer事件来调用它
George

2
@muhasturk不要更改已投票答案的含义。您的编辑使Swift早期版本的答案无效。如果您要发布Swift 2.2的更新,请发布您自己的答案。谢谢。
埃里克·阿雅

17
tap.delegate = self不需要,因为您已经设定了目标和行动
丹尼尔(Daniel)

4
在Swift3中引发错误,您的手柄点击功能应为:func handleTap(_ sender:UITapGestureRecognizer)
特拉维斯·

调用函数应该是....... func handleTap(_ sender:UITapGestureRecognizer?= nil)......您错过了“ _ “……..so您的调用功能无法正常工作。–
Prasad Patil

94

对于正在寻找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")
  }

1
isUserInteractionEnabled真的有必要吗?默认为假?
jose920405 '18

6
view.isUserInteractionEnabled = true当您的视图是ImageView或UIVIew的任何子类而不是UIControl时,此键是关键。
Pankaj Kulkarni,

61

对于Swift 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")
}

在Swift 4中,您需要明确指出触发的函数可以从Objective-C调用,因此您还需要在handleTap函数中添加@objc。

在这里查看@Ali Beadle的答案:Swift 4添加手势:覆盖vs @objc


view.isUserInteractionEnabled = true当您的视图是ImageView或UIVIew的任何子类而不是UIControl时,此键是关键。
Pankaj Kulkarni,

50

仅需注意-不要忘记在视图上启用交互:

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

view.addGestureRecognizer(tap)

// view.userInteractionEnabled = true

self.view.addSubview(view)

1
注意事项很重要!
Itai Spector

21

第1步

@IBOutlet var viewTap: UIView!

第2步

var tapGesture = UITapGestureRecognizer()

步骤: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
}

第4步

func myviewTapped(_ sender: UITapGestureRecognizer) {

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

输出值

在此处输入图片说明


14

实施轻击手势

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(_:)))
view.addGestureRecognizer(tap)
view.userInteractionEnabled = true

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

11

斯威夫特4

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

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

8

这就是它在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")
}

7

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)

不需要步骤2。
guido

7

Swift 5.1 示例的三个视图

步骤1- >添加Storyboard视图并添加Outlet ViewController UIView

@IBOutlet var firstView: UIView!
@IBOutlet var secondView: UIView!
@IBOutlet var thirdView: UIView!

步骤2- >添加storyBoard视图标签

第一视角 secondView thirdView

步骤3- >添加手势

override func viewDidLoad() {
        super.viewDidLoad()

        firstView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
        firstView.isUserInteractionEnabled = true
        secondView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
        secondView.isUserInteractionEnabled = true
        thirdView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
        thirdView.isUserInteractionEnabled = true
    }

步骤4- >选择视图

@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
        let tag = gestureRecognizer.view?.tag
        switch tag! {
        case 1 :
            print("select first view")
        case 2 :
            print("select second view")
        case 3 :
            print("select third view")
        default:
            print("default")
        }
    }

6

我很快就研究了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
}

5

如果要在下面给出目标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");
}

或者您想在下面给出快速代码,

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")
    }
}

5

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

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

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

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

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")
}

3

斯威夫特4

首先,创建一个UITapGestureRecognizer对象

var tapGesture = UITapGestureRecognizer()

第二步是初始化UITapGestureReconizer。启用用户交互,然后添加它。

override func viewDidLoad() {
        super.viewDidLoad()
    tapGesture = UITapGestureRecognizer(target: self, action: #selector(YourViewController.myviewTapped(_:)))
            infosView.isUserInteractionEnabled = true
            infosView.addGestureRecognizer(tapGesture)
view.addSubview(infosView)
}

三,创建方法

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

3

尝试以下扩展

    extension UIView {

    func  addTapGesture(action : @escaping ()->Void ){
        let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
        tap.action = action
        tap.numberOfTapsRequired = 1

        self.addGestureRecognizer(tap)
        self.isUserInteractionEnabled = true

    }
    @objc func handleTap(_ sender: MyTapGestureRecognizer) {
        sender.action!()
    }
}

class MyTapGestureRecognizer: UITapGestureRecognizer {
    var action : (()->Void)? = nil
}

然后使用它:

submitBtn.addTapGesture {
     //your code
}

你甚至可以将它用于细胞

cell.addTapGesture {
     //your code
}

1
虽然仅代码的答案确实是一个答案,但是一些解释(为什么OP的代码不起作用,代码背后的一般思想是什么,要点,警告等)可以使其成为更好的答案。
lfurini

2

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

1
加入addTapGesture()您的viewDidLoad()
Daya Kevin

1

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

  • 我在init上创建了Gesture Recognizer,并将其存储在let属性中。显然,将此手势Recog添加到视图中不起作用。可能是自身对象在初始化期间传递给了手势识别器,但配置不正确。
  • 手势识别器不应添加到零帧的视图中。我使用零帧创建所有视图,然后使用自动布局调整它们的大小。在自动布局引擎调整视图大小之后,必须添加手势识别器。因此,我在viewDidAppear中添加了手势识别器,它们可以正常工作。

1

xCode 9.3,Swift 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) {

     }
}

onSelect函数不需要是IBAction
Illya Krit

?iView中.addGestureRecognizer(轻按)gestureRecognizer的名称是clickUITapGestureRecognizer所以,正确的做法是:iView中.addGestureRecognizer(clickUITapGestureRecognizer)?
Illya Krit的

1

内部ViewDidLoad

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    self.imgMainAdView.isUserInteractionEnabled = true
    self.imgMainAdView.addGestureRecognizer(tapGestureRecognizer)

//MARK: - Image Tap Method -
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    print("Tapped")
    if let url = URL(string: self.strMAinAdvLink)
    {
        UIApplication.shared.open(url, options: [:])
    }
}

通话目的

@IBAction func btnCall1Action(_ sender: Any)
{
    let text = self.strPhoneNumber1!
    let test = String(text.filter { !" -()".contains($0) })
    UIApplication.shared.openURL(NSURL(string: "tel://\(test)")! as URL)
}

邮件目的

MFMailComposeViewControllerDelegate

 @IBAction func btnMailAction(_ sender: Any)
{
    let strEmail = SAFESTRING(str:  (self.dictEventDetails?.value(forKeyPath: "Email.value_text.email") as! String))

    if !MFMailComposeViewController.canSendMail()
    {
        AppDelegate.sharedInstance().showAlertAction(strTitle: "OK", strMessage: "Mail services are not available") { (success) in
        }
        return
    }
    let composeVC = MFMailComposeViewController()
    composeVC.mailComposeDelegate = self
    composeVC.setToRecipients([strEmail])
    composeVC.setSubject("")
    composeVC.setMessageBody("", isHTML: false)
    self.present(composeVC, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)
{
    controller.dismiss(animated: true, completion: nil)
}

1

这是在Swift 5的 View上添加手势的最简单方法

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addGestures()
    }

    // MARK: Add Gestures to target view
    func addGestures()
    {
        // 1. Single Tap or Touch
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGetstureDetected))
        tapGesture.numberOfTapsRequired = 1
        view.addGestureRecognizer(tapGesture)

        //2. Double Tap
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapGestureDetected))
        doubleTapGesture.numberOfTapsRequired = 2
        view.addGestureRecognizer(doubleTapGesture)

        //3. Swipe
        let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGetstureDetected))
        view.addGestureRecognizer(swipeGesture)

        //4. Pinch
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(self.pinchGetstureDetected))
        view.addGestureRecognizer(pinchGesture)

        //5. Long Press
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGetstureDetected))
        view.addGestureRecognizer(longPressGesture)

        //6. Pan
        let panGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.panGestureDetected))
        view.addGestureRecognizer(panGesture)

    }

    // MARK: Handle Gesture detection
    @objc func swipeGetstureDetected() {
        print("Swipe Gesture detected!!")
    }

    @objc func tapGetstureDetected() {
        print("Touch/Tap Gesture detected!!")
    }

    @objc func pinchGetstureDetected() {
        print("Pinch Gesture detected!!")
    }

    @objc func longPressGetstureDetected() {
        print("Long Press Gesture detected!!")
    }

    @objc func doubleTapGestureDetected() {
        print("Double Tap Gesture detected!!")
    }

    @objc func panGestureDetected()
    {
        print("Pan Gesture detected!!")
    }


    //MARK: Shake Gesture
    override func becomeFirstResponder() -> Bool {
        return true
    }
    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){
        if motion == .motionShake
        {
            print("Shake Gesture Detected")
        }
    }
}

0

尝试以下快速代码(在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);
        }
      }
    }

请注意,您的目标可以是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!)
      }
    }

0

您可以直接调用该handleTap函数,而不必调用myView的UITapGestureRecognizer ,

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.