본문 바로가기
YAGOM CAREER STARTER

[TIL] 20230317: Responder Chain / Touch Event

by Rhode 2023. 3. 18.

본문은 야곰 아카데미 커리어 스타터 캠프를 통해 학습한 내용을 회고한 글입니다.


Touch Event Handling 사용

import UIKit

class ViewController: UIViewController {
    var horizontalDirectionText = String()
    var verticalDirectionText = String()
    
    var touchLocation: CGPoint = CGPoint(x: 0, y: 0) {
        didSet {
            if touchLocation.x > oldValue.x {
                horizontalDirectionText = "우"
            } else if touchLocation.x < oldValue.x {
                horizontalDirectionText = "좌"
            } else {
                horizontalDirectionText = ""
            }
            if touchLocation.y > oldValue.y {
                verticalDirectionText = "하"
            } else if touchLocation.y < oldValue.y {
                verticalDirectionText = "상"
            } else {
                verticalDirectionText = ""
            }
        }
    }
    
    @IBOutlet weak var touchHandlerLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let theTouch = touches.first else { return }
        
        touchLocation = theTouch.location(in: self.view)
        displayTouchHandlerLabel()
    }
    
    func displayTouchHandlerLabel() {
        touchHandlerLabel.text = horizontalDirectionText + verticalDirectionText + "향"
    }
    
}