ios개발

<ios개발> swift 애니메이션 - 라벨 흔들기

studying develop 2021. 6. 20. 10:04
//: A UIKit based Playground for presenting user interface
  
import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black
        
        view.addSubview(label)
        self.view = view
        
        label.shake(count: 0)
    }
}

extension UIView {
    func shake(completion: (() -> Void)? = nil, count: Int?) {
        
        let duration: TimeInterval = 10
        var animationDelays: [CGFloat] = []

        let shakeAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 0.5)
        
        var xPos: [CGFloat] = [-100,0,100,0]
        var yPos: [CGFloat] = [0,0,0,0]
        
        guard xPos.count == yPos.count else {
            return
        }
        
        for i in 0..<xPos.count {
            xPos[i] = xPos[i]
            yPos[i] = yPos[i]
            
            animationDelays.append( CGFloat(i) * (1.0 / CGFloat(xPos.count) ))
        }
        
        for i in 0..<xPos.count {
            print("animation added")
            
            shakeAnimator.addAnimations({
                self.transform = CGAffineTransform(translationX: xPos[i], y: yPos[i])
            }, delayFactor: animationDelays[i])
        }
 
        shakeAnimator.addCompletion { _ in
            print("animation finished!")
        }
    
        shakeAnimator.startAnimation()
        
    }
}


// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()