UITapGestureRecognizer

在这种情况下,使用目标 selfaction 初始化 UITapGestureRecognizeraction 是具有单个参数的方法:UITapGestureRecognizer

初始化后,将其添加到应识别其中的点击视图中。

迅速

override func viewDidLoad() {
    super.viewDidLoad()
    let recognizer = UITapGestureRecognizer(target: self,
                                            action: #selector(handleTap(_:)))
    view.addGestureRecognizer(recognizer)
}

func handleTap(recognizer: UITapGestureRecognizer) {

}

Objective-C

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *recognizer =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(handleTap:)];
    [self.view addGestureRecognizer:recognizer];
}

- (void)handleTap:(UITapGestureRecognizer *)recognizer {

}  

通过 UITapGestureRecognizer 解除键盘的示例:

首先,创建解除键盘的功能:

func dismissKeyboard() {
        view.endEditing(true)
    }  

然后,在视图控制器中添加一个轻击手势识别器,调用我们刚刚制作的方法

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
        view.addGestureRecognizer(tap)

获取手势位置的示例 UITapGestureRecognizer(Swift 3):

func handleTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
if gestureRecognizer.state == UIGestureRecognizerState.recognized
   {
     print(gestureRecognizer.location(in: gestureRecognizer.view))
   }
}