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