套用按鈕效果至所有ViewController

YiChing
獨立 APP 開發基地
5 min readMay 7, 2019

本文實作將同樣的動畫響應效果套用至所有 ViewController,只要兩步驟,就能把所有按鈕一次一起套用相同效果!

成果示意圖

第一步:實作代碼如下

import UIKit//自訂一個class繼承UIButton
class BounceButton: UIButton {
//isCurrentOutside用於防止用戶在touchDragOutside與touchDragInside之間做切換時發生「跳針」的問題。換句話說,因為在按鈕放大縮小時,按鈕邊界判斷Outside與Inside容易會出問題。
var isCurrentOutside = false
override func awakeFromNib() {
super.awakeFromNib()
self.addTarget(self, action: #selector(shrinkAllowAnimation), for: .touchDown)
self.addTarget(self, action: #selector(restoreAllowAnimation), for: .touchUpInside)
self.addTarget(self, action: #selector(restoreAllowAnimation), for: .touchUpOutside)
self.addTarget(self, action: #selector(restore), for: .touchDragOutside)
self.addTarget(self, action: #selector(shrink), for: .touchDragInside)
}
@objc func shrinkAllowAnimation(){
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: CGFloat(0.6),
initialSpringVelocity: CGFloat(25.0),
options: [.curveEaseOut, .allowUserInteraction],
animations: {
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
})
}
@objc func restoreAllowAnimation(){
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: CGFloat(0.6),
initialSpringVelocity: CGFloat(10.0),
options: [.curveEaseIn, .allowUserInteraction],
animations: {
self.transform = CGAffineTransform.identity
})
}
@objc func shrink(){
if isCurrentOutside == true{
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: CGFloat(0.6),
initialSpringVelocity: CGFloat(15.0),
options: [.curveEaseOut],
animations: {
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}, completion: {_ in self.isCurrentOutside = false})
}
}
@objc func restore(){
if isCurrentOutside == false{
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: CGFloat(0.6),
initialSpringVelocity: CGFloat(15.0),
options: [.curveEaseIn],
animations: {
self.transform = CGAffineTransform.identity
},completion: {_ in self.isCurrentOutside = true})
}
}
//阻止系統預設的Highlight效果。阻止按下按鈕後文字呈現半透明的狀態。
override var isHighlighted: Bool {
didSet { if isHighlighted { isHighlighted = false } }
}
}

第二步:修改 storyboard 按鈕中的 class,如下圖所示

只要調整每個欲套用效果的按鈕的 class,就能輕鬆套用效果!

更多效果:

結語

如果有覺得文章幫助到了你,請不要吝嗇為我拍手鼓勵唷!未來也將持續分享類似的小小開發心得,歡迎追蹤!

下載檔案

CustomButton

關鍵字:UIButton, animation, all buttons, same attributes, same animation, custom class, touchDown, touchUpInside

--

--