[swift] 터치 이벤트 처리를 위한 UIView에서의 UIResponder 사용법

iOS 앱을 개발할 때 터치 이벤트를 처리해야 하는 경우가 많이 있습니다. UIView 클래스는 UIResponder를 상속하고 있어 터치 이벤트를 처리할 수 있는 기능을 제공합니다. 이번 블로그 포스트에서는 UIView에서 UIResponder를 사용하여 터치 이벤트를 처리하는 방법을 알아보겠습니다.

1. UIResponder로 터치 이벤트 받아오기

UIView에서 터치 이벤트를 받기 위해 UIResponder를 오버라이드해야 합니다. 아래와 같이 UIResponder를 상속받는 클래스를 만들어 봅시다.

class CustomView: UIView {
    // UIResponder 오버라이드
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        
        // 터치가 시작되었을 때 실행할 코드 작성
        // ...
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        
        // 터치가 이동할 때 실행할 코드 작성
        // ...
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        
        // 터치가 끝났을 때 실행할 코드 작성
        // ...
    }
}

위의 코드에서 touchesBegan, touchesMoved, touchesEnded 메서드를 오버라이드하여 터치 이벤트를 처리합니다. 각각의 메서드에서 터치 이벤트에 대한 코드를 작성할 수 있습니다.

2. 터치 이벤트에 따른 동작 구현

터치 이벤트에 따라 원하는 동작을 구현할 수 있습니다. 예를 들어, 터치가 시작되었을 때 해당 뷰의 배경색을 변경하고, 터치가 이동할 때 뷰를 이동시키며, 터치가 끝났을 때 원래의 배경색으로 되돌리는 동작을 구현해보겠습니다.

class CustomView: UIView {
    var originalColor: UIColor?
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        
        // 터치가 시작되었을 때 배경색 변경
        originalColor = backgroundColor
        backgroundColor = .blue
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        
        // 터치가 이동할 때 위치 변경
        if let touch = touches.first {
            let newPosition = touch.location(in: self.superview)
            self.center = newPosition
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        
        // 터치가 끝났을 때 배경색 복원
        backgroundColor = originalColor
    }
}

위의 코드에서는 touchesBegan에서 터치가 시작되면 배경색을 파란색으로 변경하고, touchesMoved에서 터치가 이동하면 뷰의 위치도 함께 이동시킵니다. 마지막으로 touchesEnded에서 터치가 끝나면 원래의 배경색으로 되돌리는 동작을 구현합니다. originalColor 변수를 사용하여 터치 이벤트 전의 배경색을 저장하고 복원하는데 사용합니다.

3. 사용 예시

이제 CustomView를 사용하여 터치 이벤트를 처리하는 예시를 확인해보겠습니다.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let customView = CustomView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
        customView.backgroundColor = .green
        view.addSubview(customView)
    }
}

위의 코드에서는 UIViewController에서 CustomView를 생성하고, 배경색을 초록색으로 설정한 후에 해당 뷰를 추가하였습니다. 이제 앱을 실행해보면 CustomView에 대한 터치 이벤트가 처리되는 것을 확인할 수 있습니다.

이렇게 UIResponder를 상속하여 UIView에서 터치 이벤트를 처리할 수 있습니다. 추가적으로 터치 이벤트에 대한 다양한 처리를 구현하고 싶다면 UIResponder의 다른 메서드들을 참고해보세요.

참고 자료: