今回は、UIButtonにおいてタップした際に押し込んでいるよう見えるアニメーションを紹介いたします。
アプリやブラウザ内にあるボタンなどのタップしたりするコンポーネントには、物理ボタンではない故に押した際に何かしらの反応をさせるものが多いです。
その反応を実現する方法として、
下記のようなコードにより、UIButtonの押し込みのアニメーションを実現させることが出来ます.。
var animationButton = UIButton()
...
...
animationButton.addTarget(self, action: #selector(self.pushButton_Animation(_:)), for: .touchDown)
animationButton.addTarget(self, action: #selector(self.separateButton_Animation(_:)), for: .touchUpInside)
...
...
@objc func pushButton_Animation(_ sender: UIButton){
UIView.animate(withDuration: 0.1, animations:{ () -> Void in
sender.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
})
}
@objc func separateButton_Animation(_ sender: UIButton){
UIView.animate(withDuration: 0.2, animations:{ () -> Void in
sender.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
sender.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
}