[swift] Swift Core Animation으로 뷰를 흔들거나 요동치게 만들기

뷰 애니메이션은 사용자 인터페이스를 더 동적이고 흥미롭게 만들 수 있는 강력한 기능입니다. Swift에서는 Core Animation 프레임워크를 사용하여 뷰를 흔들거나 요동치게 만들 수 있습니다. 본 포스트에서는 Swift Core Animation을 사용하여 뷰를 흔들거나 요동치게 만드는 방법을 알아보겠습니다.

Prerequisites

Step 1: Core Animation 프레임워크 가져오기

첫 번째 단계로, Core Animation 프레임워크를 프로젝트에 가져와야 합니다. 이를 위해 import QuartzCore 코드를 추가하거나, Xcode에서 프로젝트 타겟 설정에서 QuartzCore.framework를 추가합니다.

Step 2: UIView extension 작성

뷰를 흔들거나 요동치게 만들기 위해, UIView의 extension을 작성해야 합니다. 아래의 코드를 UIView+Shake.swift 파일에 추가합니다.

import UIKit

extension UIView {
    func shake() {
        let shakeAnimation = CABasicAnimation(keyPath: "position")
        shakeAnimation.duration = 0.05
        shakeAnimation.repeatCount = 5
        shakeAnimation.autoreverses = true
        shakeAnimation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 5, y: self.center.y))
        shakeAnimation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 5, y: self.center.y))
        self.layer.add(shakeAnimation, forKey: "position")
    }
}

Step 3: 뷰 흔들기

이제 뷰를 흔들 수 있는 shake() 메서드를 사용할 수 있습니다. 아래의 코드를 통해 뷰를 흔들어보세요.

view.shake()

Step 4: 뷰 요동치게 만들기

요동치는 애니메이션을 구현하기 위해, CABasicAnimation을 사용합니다. 이제 뷰를 요동치게 만들어보세요.

extension UIView {
    func wobble() {
        let wobbleAnimation = CAKeyframeAnimation(keyPath: "transform.rotation")
        wobbleAnimation.values = [-0.05, 0.05, -0.03, 0.03, -0.01, 0.01, 0]
        wobbleAnimation.duration = 0.1
        wobbleAnimation.repeatCount = 5
        self.layer.add(wobbleAnimation, forKey: "transform.rotation")
    }
}

뷰를 요동치게 하려면 아래의 코드를 사용하세요.

view.wobble()

마무리

이제 Swift Core Animation을 사용하여 뷰를 흔들거나 요동치게 만들 수 있습니다. 뷰 애니메이션은 사용자 인터페이스를 더 흥미롭게 만들 수 있는 효과적인 방법입니다. 사용법을 응용하여 다양한 애니메이션을 만들어 보세요.

참고 자료