iOS UITapGestureRecognizer

示例

在这种情况下,UITapGestureRecognizer使用目标self和初始化,该目标action是一个具有单个参数的方法:a UITapGestureRecognizer。

初始化后,将其添加到应该可以识别轻敲的视图中。

迅速

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

func handleTap(recognizer: UITapGestureRecognizer) {

}

目标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")
ifgestureRecognizer.state== UIGestureRecognizerState.recognized
   {
     print(gestureRecognizer.location(in: gestureRecognizer.view))
   }
}