적당한 고통은 희열이다

- 댄 브라운 '다빈치 코드' 중에서

Swift iOS 앱 개발/Swift

[Swift iOS] UIGestureRecognizer 터치 이벤트 제어하기

hongssup_ 2020. 12. 28. 12:02
반응형

UIGestureRecognizer

 

Swift 에서 터치 이벤트를 구현해주는 아주 편리한 헬퍼 클라스!!

UIGestureRecognizer 의 subclass 들에는 아래 항목들이 있다. 

- UITapGestureRecognizer

- UIPinchGestureRecognizer

- UIRotationGestureRecognizer

- UISwipeGestureRecognizer

- UIPanGestureRecognizer

- UIScreenEdgePanGestureRecognizer

- UILongPressGestureRecognizer

 

1. UITapGestureRecognizer

터치 이벤트 함수는 다음과 같이 작성할 수 있다.

@objc func handleTap(sender: UITapGestureRecognizer) {
    if sender.state == .ended {
        // handling code
    }
}

원하는 결과 값을 넣은 함수를 작성한 후에는

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
//tap.numberOfTapsRequired = 2 
myView.addGestureRecognizer(tap)
//myView.isUserInteractionEnabled = true

를 setupView()에 추가해주어 함수를 작동시킬 수 있도록 한다. 

 

2. UISwipeGestureRecognizer

let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeRight.direction = .right
//swipe.numberOfTouchesRequired = 1
myView.addGestureRecognizer(swipeRight)
//myView.isUserInteractionEnabled = true

let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeLeft.direction = .left
myView.addGestureRecognizer(swipeLeft)

뷰컨트롤러의 viewDidLoad() 안에 위와 같이 선언해주어 다음 메서드를 실행한다.  

@objc func handleSwipe(sender: UISwipeGestureRecognizer) {
    switch sender.direction {
    case .right:
        print("swipeRight")
        break
    case .left:
        print("swipeLeft")
        break
    default:
        break
    }  
}

 

3. UIPanGestureRecognizer

myView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan)))
@objc func handlePan(gesture: UIPanGestureRecognizer) {
    switch gesture.state {
    case .began:
        print("began")
        break
    case .changed:
        let translation = gesture.translation(in: swipeView)
        view1.transform = CGAffineTransform(translationX: translation.x, y: 0)
        break
    case .ended:
        UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseOut, animations: { self.view1.transform = .identity })
        break
    default:
        break
    }
}
728x90
반응형