Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] touches 제스쳐 (touchesBegin, touchesMoved, touchesEnded, touchesCancelled) 본문

iOS 응용 (swift)

[iOS - swift] touches 제스쳐 (touchesBegin, touchesMoved, touchesEnded, touchesCancelled)

jake-kim 2022. 3. 26. 21:07

touches 제스쳐

  • touches 제스쳐는 UIResponder에 기본적으로 구현되어 있는 메소드로 4가지가 존재
// UIResponder

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEstimatedPropertiesUpdated:(NSSet<UITouch *> *)touches API_AVAILABLE(ios(9.1));
  • UIView와 UIViewController는 UIResponder를 상속받고 있으므로, 모든 UIView는 4가지 메소드를 사용 가능

https://seizze.github.io/2019/11/26/iOS%EC%9D%98-Responder%EC%99%80-Responder-Chain-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0.html

touches 제스쳐 4가지

  • touchesBegan: 화면을 클릭하기 시작할 때 실행
  • touchesMoved: 화면에 드래그 했을 때 실행
  • touchesEnded: 화면을 클릭 후 뗄 때 실행
  • touchesCancelled: 위 3가지 이벤트가 발생도중에 system alert와 같은게 발생한 경우, touchesCanclled 발생

https://developer.apple.com/documentation/uikit/uiresponder/1621116-touchescancelled

예제 전체 코드)

import UIKit

class ViewController: UIViewController {
  
  private lazy var toucheLabel: UILabel = {
    let label = UILabel()
    label.text = "label"
    label.font = .systemFont(ofSize: 24)
    label.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(label)
    return label
  }()

  override func viewDidLoad() {
    super.viewDidLoad()
    
    self.view.addSubview(self.toucheLabel)
    NSLayoutConstraint.activate([
      self.toucheLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
      self.toucheLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
    ])
  }

  var beganCount = 0
  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    self.beganCount += 1
    self.toucheLabel.text = "touchesBegan \(self.beganCount)"
  }

  var movedCount = 0
  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesMoved(touches, with: event)
    self.movedCount += 1
    self.toucheLabel.text = "touchesMoved \(self.movedCount)"
  }

  var endedCount = 0
  override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    self.endedCount += 1
    self.toucheLabel.text = "touchesEnded \(self.endedCount)"
  }

  var cancelledCount = 0
  override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesCancelled(touches, with: event)
    self.cancelledCount += 1
    self.toucheLabel.text = "touchesCancelled \(self.cancelledCount)"
  }
}
Comments