今回はUIViewやUIButtonをアニメーションさせる方法をご紹介します。
まずはアニメーションさせる適当なViewを作成します。
let sampleView = UIView()
sampleView.frame.size = CGSize(width: 120, height: 120)
sampleView.center = CGPoint(x: 60, y: 60)
sampleView.backgroundColor = UIColor.white
sampleView.layer.borderColor = UIColor.cyan.cgColor
sampleView.layer.borderWidth = 2
view.addSubview(sampleView)
作成したViewをアニメーションさせるにはUIView.animateメソッドを使用します。
ここでは大きさを変更してみましょう。
中心点も設定しているのは、大きさを変更すると左上を起点に大きさが変わってしまうためです。
UIView.animate(withDuration: 0.5, animations: {
    self.sampleView.frame.size = CGSize(width: 80, height: 80)
    self.sampleView.center = CGPoint(x: 60, y: 60)
}, completion: { Void in
    // アニメーション完了時の処理を記述します
})
次に、大きさと角丸の半径をアニメーションで変更してみたいと思います。
サンプルとして、標準カメラアプリの動画撮影ボタンのようなボタンを作成してみましょう。
実際の撮影処理はしていません。
まずは必要な宣言
let shutterView = UIView()
let shutterButton = UIButton()
var isRecording: Bool = false
Viewを作成するメソッドを作成します。
func makeShutterView() {
    shutterView.frame.size = CGSize(width: 74, height: 74)
    shutterView.center = CGPoint(x: 45, y: 45)
    let shutterCircle = UIView()
    shutterCircle.frame.size = CGSize(width: 76, height: 76)
    shutterCircle.center = CGPoint(x: 45, y: 45)
    shutterCircle.layer.borderColor = UIColor.white.cgColor
    shutterCircle.layer.borderWidth = 4
    shutterCircle.layer.cornerRadius = 38.0
    shutterView.addSubview(shutterCircle)
    shutterButton.frame.size = CGSize(width: 60, height: 60)
    shutterButton.center = CGPoint(x: 45, y: 45)
    shutterButton.backgroundColor = UIColor.red
    shutterButton.layer.cornerRadius = 30.0
    shutterButton.addTarget(self, action: #selector(onClickRecordingButton), for: .touchUpInside)
    shutterView.addSubview(shutterButton)
    view.addSubview(shutterView)
}
 続きを読む…»