본문 바로가기

iOS/스위프트로 아이폰 앱 만들기

[18장] Swipe Gesture

728x90

Swipe gesture는 화면을 터치한 상태에서 손가락을 미는 동작입니다.

 

 

Swipe gesture 인식하기

UISwipeGestureRecognizer를 view의 gestureRecognizer에 추가하여, swipe gesture를 인식할 수 있도록 했습니다.

action으로 특정한 함수를 추가하여 swipe gesture 발생 시 수행할 동작을 추가할 수 있습니다.

numberOfTouchesRequired 속성을 변경해서 스와이프에 필요한 손가락 개수도 지정할 수 있습니다.

class ViewController: UIViewController {
    let numOfTouchs = 2
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 손가락 1개인 경우
        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
        swipeUp.direction = UISwipeGestureRecognizer.Direction.up
        self.view.addGestureRecognizer(swipeUp)
        
        // 손가락 2개인 경우
        let swipeUpMulti = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGestureMulti(_:)))
        swipeUpMulti.direction = UISwipeGestureRecognizer.Direction.up
        swipeUpMulti.numberOfTouchesRequired = numOfTouchs
        self.view.addGestureRecognizer(swipeUpMulti)

    }

    @objc func respondToSwipeGesture(_ gesture: UIGestureRecognizer) {
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
            case UISwipeGestureRecognizer.Direction.up:
                imgViewUp.image = imgUp[1]
            case UISwipeGestureRecognizer.Direction.down:
                imgViewDown.image = imgDown[1]
            case UISwipeGestureRecognizer.Direction.left:
                imgViewLeft.image = imgLeft[1]
            case UISwipeGestureRecognizer.Direction.right:
                imgViewRight.image = imgRight[1]
            default:
                break
            }
        }
    }
    
    @objc func respondToSwipeGestureMulti(_ gesture: UIGestureRecognizer) {
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
            case UISwipeGestureRecognizer.Direction.up:
                imgViewUp.image = imgUp[2]
            case UISwipeGestureRecognizer.Direction.down:
                imgViewDown.image = imgDown[2]
            case UISwipeGestureRecognizer.Direction.left:
                imgViewLeft.image = imgLeft[2]
            case UISwipeGestureRecognizer.Direction.right:
                imgViewRight.image = imgRight[2]
            default:
                break
            }
        }
    }
}

'iOS > 스위프트로 아이폰 앱 만들기' 카테고리의 다른 글

[후기] - Do it! 스위프트로 아이폰 앱 만들기  (0) 2021.10.21
[19장] pinch gesture  (0) 2021.10.20
[17장] Tab & Touch  (0) 2021.10.20
[16장] Core graphics  (0) 2021.10.19
[15장] Camera & Photo Library  (0) 2021.10.19