iOS/코드조각

[iOS, Swift] UISwipeGestureRecognizer 예제

검은참깨두유vm 2022. 8. 25. 10:15
반응형

iOS 15.5, Xcode 13.31, Swift 5, UIKit 환경에서 진행했습니다.

 

class UISwipeViewController: UIViewController {
    
    lazy var label: UILabel = {
        var label = UILabel()
        label.text = "initial label"
        label.frame = CGRect(x: 100, y: 100, width: 200, height: 20)
        label.backgroundColor = .lightGray
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(label)
        
        let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
        let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
        swipeRightGesture.direction = UISwipeGestureRecognizer.Direction.right
        swipeLeftGesture.direction = UISwipeGestureRecognizer.Direction.left
        view.addGestureRecognizer(swipeRightGesture)
        view.addGestureRecognizer(swipeLeftGesture)
    }
    
    @objc func handleSwipe(_ gesture: UISwipeGestureRecognizer) {
        label.text = "Swipe recognized"
        
        if gesture.direction == UISwipeGestureRecognizer.Direction.right {
            label.text = "Swipe right"
        } else if gesture.direction == UISwipeGestureRecognizer.Direction.left {
            label.text = "Swipe left"
        }
    }
    
}

 

Swipe 기능을 사용하려는 뷰에 addGestureRecognizer 메소드를 통해 Swipe 제스쳐를 등록하여 스와이프 기능을 사용할 수 있다.

 

 

 

반응형