개발아 담하자

[iOS/Swift] Tap Gesture Recognizer 사용해 키보드 닫기 본문

📱 iOS

[iOS/Swift] Tap Gesture Recognizer 사용해 키보드 닫기

choidam 2020. 3. 12. 18:47

간단하지만 정말 활용도가 높은 gesture recognizer를 사용해보자~!

 

1. VC 에 Tap Gesture Recognizer 를 추가한다.

 

2. delegate 시켜준다.

class ViewController: UIViewController, UIGestureRecognizerDelegate {

   ...
   
}

 

3. gestureRecognizer 메소드를 작성한다.

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        self.view.endEditing(true)
        return true
    }

 

4. viewDidLoad 에 tap gesture 를 추가한다.

   let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer()
   tapGesture.delegate = self
        
   self.view.addGestureRecognizer(tapGesture)

 

5. 확인!

 


full source code

import UIKit

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer()
        tapGesture.delegate = self
        
        self.view.addGestureRecognizer(tapGesture)
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        self.view.endEditing(true)
        return true
    }
}