[swift] Swift Core Animation의 애니메이션과 제스처 인식

이 포스트에서는 Swift Core Animation 프레임워크를 사용하여 iOS 애플리케이션에서 애니메이션을 만들고, 제스처 인식을 구현하는 방법에 대해 알아보겠습니다.

목차

애니메이션

기본 애니메이션

Swift Core Animation을 사용하여 애니메이션을 만드는 가장 기본적인 방법은 CABasicAnimation 클래스를 사용하는 것입니다. 다음은 CABasicAnimation을 사용하여 UIViewalpha 프로퍼티를 애니메이션하는 예제입니다.

let animation = CABasicAnimation(keyPath: "alpha")
animation.fromValue = 1.0
animation.toValue = 0.0
animation.duration = 1.0

yourView.layer.add(animation, forKey: "alphaAnimation")

키프레임 애니메이션

키프레임 애니메이션은 여러 개의 중간 프레임을 정의하여 순차적으로 애니메이션을 실행하는 방식입니다. CAKeyframeAnimation 클래스를 사용하여 키프레임 애니메이션을 구현할 수 있습니다. 다음은 CAKeyframeAnimation을 사용하여 UIView의 위치를 애니메이션하는 예제입니다.

let animation = CAKeyframeAnimation(keyPath: "position")
animation.values = [CGPoint(x: 0, y: 0), CGPoint(x: 100, y: 100), CGPoint(x: 200, y: 200)]
animation.duration = 1.0

yourView.layer.add(animation, forKey: "positionAnimation")

애니메이션 그룹

여러 개의 애니메이션을 그룹으로 묶어 동시에 실행하는 방법도 있습니다. CAAnimationGroup 클래스를 사용하여 애니메이션 그룹을 구현할 수 있습니다. 다음은 CAAnimationGroup을 사용하여 UIView의 크기와 회전을 애니메이션하는 예제입니다.

let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 1.0
scaleAnimation.toValue = 2.0

let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = CGFloat.pi

let animationGroup = CAAnimationGroup()
animationGroup.animations = [scaleAnimation, rotationAnimation]
animationGroup.duration = 1.0

yourView.layer.add(animationGroup, forKey: "groupAnimation")

제스처 인식

탭 제스처

UITapGestureRecognizer 클래스를 사용하여 탭 제스처를 인식할 수 있습니다. 다음은 UITapGestureRecognizer을 사용하여 UIView를 탭했을 때 호출되는 메서드를 구현하는 예제입니다.

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
yourView.addGestureRecognizer(tapGesture)

@objc func handleTap(sender: UITapGestureRecognizer) {
    // 탭 제스처 이벤트 처리
}

스와이프 제스처

UISwipeGestureRecognizer 클래스를 사용하여 스와이프 제스처를 인식할 수 있습니다. 다음은 UISwipeGestureRecognizer을 사용하여 UIView를 스와이프했을 때 호출되는 메서드를 구현하는 예제입니다.

let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
yourView.addGestureRecognizer(swipeGesture)

@objc func handleSwipe(sender: UISwipeGestureRecognizer) {
    // 스와이프 제스처 이벤트 처리
}

핀치 제스처

UIPinchGestureRecognizer 클래스를 사용하여 핀치 제스처를 인식할 수 있습니다. 다음은 UIPinchGestureRecognizer을 사용하여 UIView를 핀치했을 때 호출되는 메서드를 구현하는 예제입니다.

let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch))
yourView.addGestureRecognizer(pinchGesture)

@objc func handlePinch(sender: UIPinchGestureRecognizer) {
    // 핀치 제스처 이벤트 처리
}

이제 Swift Core Animation의 애니메이션과 제스처 인식에 대해 간단히 알아보았습니다. 더 다양한 애니메이션과 제스처 인식을 구현하기 위해 해당 클래스와 프로퍼티의 문서를 참고해보세요.

참고 자료