ios-如何在我的应用程序中实现UITapGestureRecognizer

我对编程和目标C还是很陌生。我想知道如何制作一个具有空白屏幕和一分钟的计时器的应用程序。 您应该尽可能快地,尽可能长地点击。 我想知道如何在代码中实现UITapGestureRecognizer

4个解决方案
94 votes

这是有关如何在您的课堂中实现手势识别器的分步指南:

  1. 使您的课程符合tapGestureRecognizer.delegate = self; 协议。

  2. 实例化手势识别器。 例如,要实例化tapGestureRecognizer.delegate = self; ,我们将执行以下操作:

    tapGestureRecognizer.delegate = self;
    

    在这里,动作是将处理手势的选择器。 在这里,我们的选择器handleTapFrom将看起来像:

    tapGestureRecognizer.delegate = self;
    

    选择器的参数是手势识别器。 我们可以使用此手势识别器访问其属性,例如,我们可以找到手势识别器的状态,例如tapGestureRecognizer.delegate = self; numberOfTapsRequired等。

  3. 在实例化的手势识别器上设置所需的属性。 例如,对于tapGestureRecognizer.delegate = self; ,我们可以设置属性numberOfTapsRequirednumberOfTouchesRequired

  4. 将手势识别器添加到要为其检测手势的视图。 在我们的示例代码中(我将共享该代码供您参考),我们将使用以下代码行将手势识别器添加到imageView:

    tapGestureRecognizer.delegate = self;
    
  5. 将手势识别器添加到视图后,设置手势识别器的委托,即将处理所有手势识别器内容的类。 在我们的示例代码中,它将像:

    tapGestureRecognizer.delegate = self;
    

    注意:将手势识别器添加到视图后,分配委托。 否则,将不会调用该操作方法。

Mathew Varghese answered 2020-08-07T03:12:32Z
14 votes

Swift中的示例:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var myUIImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "myUIImageViewTapped:")
        singleTap.numberOfTapsRequired = 1
        singleTap.numberOfTouchesRequired = 1
        self.myUIImageView.addGestureRecognizer(singleTap)
        self.myUIImageView.userInteractionEnabled = true
    }

    func myUIImageViewTapped(recognizer: UITapGestureRecognizer) {
        if(recognizer.state == UIGestureRecognizerState.Ended){
            println("myUIImageView has been tapped by the user.")
        }
    }

}
King-Wizard answered 2020-08-07T03:12:51Z
14 votes
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.tableView addGestureRecognizer:gestureRecognizer];
self.tableView.userInteractionEnabled = YES;
gestureRecognizer.cancelsTouchesInView = NO;  // this prevents the gesture recognizers to 'block' touches
Albert Renshaw answered 2020-08-07T03:13:07Z
0 votes

如果您正在使用Swift(iOS9)和SpriteKit,请尝试以下操作。

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        let singleTap = UITapGestureRecognizer(target:self, action:#selector(self.handleSingleTap:))
        singleTap.numberOfTouchesRequired = 1
        singleTap.addTarget(self, action:#selector(self.handleSingleTap))
        view.userInteractionEnabled = true
        view.addGestureRecognizer(singleTap)
    }
    //event handler
    func handleSingleTap(sender:UITapGestureRecognizer){
        print("tapped")
    }
}
dbbudd answered 2020-08-07T03:13:27Z
translate from https://stackoverflow.com:/questions/11355671/how-do-i-implement-the-uitapgesturerecognizer-into-my-application