반응형
Swift 에서 터치 이벤트를 구현해주는 아주 편리한 헬퍼 클라스!!
UIGestureRecognizer 의 subclass 들에는 아래 항목들이 있다.
- 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
반응형
'Swift iOS 앱 개발 > Swift' 카테고리의 다른 글
[Swift iOS] 상단 NavigationBar 설정 (0) | 2021.03.11 |
---|---|
[Swift UIKit] All about UIButton() (0) | 2021.03.11 |
[Swift] higher order function? (0) | 2021.01.18 |
[Swift 용어] Value Type / Reference Type (0) | 2020.12.26 |
[Swift 용어] Closures 클로저란? (1) | 2020.12.20 |