ずっと5月

3日坊主してます

UIViewのアニメーションについてのメモ

UIView.animateによるアニメーション

duration は何秒でアニメーションさせるか
delay で開始まで何秒遅延するか指定
options でアニメーションの動き方を指定 (後述)
animations で動かしたいUIViewのプロパティを変化
completion は完了した後に呼ばれるクロージャ

// optionsを複数指定したい場合は[.repeat,.autoreverse, xx, xx...]な感じで指定する
UIView.animate(withDuration: 1.0,
                       delay: 0.0,
                       options: .autoreverse,
                       animations: {
                        self.squareView.center.y += 100.0
                       },
                       completion: nil)

f:id:uminokaze521:20210301213828g:plain

UIView.transitionによるアニメーション

UIView.transition(with: self.squareView,
                          duration: 1.0,
                          options: [.transitionFlipFromLeft, .repeat, .autoreverse],
                          animations: {
                            self.squareView.backgroundColor = UIColor.yellow
        },
                          completion:  { (finished: Bool) in
                            self.squareView.backgroundColor = UIColor.blue
        })

f:id:uminokaze521:20210301221715g:plain

optionsについて

指定できるoptionはたくさんあるのでめぼしいものをメモしておく

option名 説明
autoreverse 逆再生する
repeat 繰り返し
curveEaseIn アニメーションが進行するにつれて早くなる
curveEaseIn アニメーションが進行するにつれて早くなり、完了する前に再び遅くなる
curveEaseOut アニメーションが進行するにつれて遅くなる
curveLinear 等速
transitionFlipFromLeft 垂直軸を中心に左から右に反転する
transitionFlipFromRight 垂直軸を中心に右から左に反転する
transitionFlipFromTop 水平軸を中心に上から下に反転する
transitionFlipFromBottom 水平軸を中心に下から上に反転するトランジション

複数の処理を連続的に行う

open class func addKeyframe(withRelativeStartTime frameStartTime: Double, relativeDuration frameDuration: Double, animations: @escaping () -> Swift.Void)

を使う

UIView.animateKeyframes(withDuration: 2.0, delay: 0.0, options: [.repeat], animations: {

            UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1, animations: {
                self.squareView.center.y += 100.0
                self.squareView.center.x += 100.0
                self.squareView.transform = CGAffineTransform(rotationAngle: 360)
            })

            UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 1, animations: {
                self.squareView.center.y -= 100.0
                self.squareView.center.x -= 100.0
                self.squareView.transform = CGAffineTransform(rotationAngle: 360)
            })

        }, completion: nil)

参考

qiita.com