UILongPressGestureRecognizer
사용법
- 만약 라벨에 LongPressGesture를 만들어주고 싶으면
let tempLabel = UILabel()
let longPressGesture = UILongPressGestureRecognizer()
longPressGesture.addTarget(self, action: #selector(didPress))
label.addGestureRecognizer(longPressGesture)
@objc func didPress() {
print("Did Press!!")
}
- 이렇게 해서 실행해보면 아마 아무일도 안일어날텐데, 다음 코드를 작성해줘야한다
tempLabel.isUserInteractionEnabled = true
문제
- 이제 실행해서 길게 눌러보면 "Did Press!!"가 2번 찍히게 되는데
- 이는 길게 누르기 시작했을 때와 누르기가 끝났을 때, 2가지로 나뉘기 때문이다
- 따라서 이를 분리하고 싶으면 다음처럼 쓰면 된다
@objc func didPress(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
print("began Did Press!!")
}
if sender.state == .ended {
print("ended Did Press!!")
}
}