onthewavesのコードスニペット

SwiftやObjective-Cを中心にiPhoneアプリ開発に関するコードスニペットを書きます。

コードスニペット (UIButton編)ボタン押下時のアニメーション

ボタン押下時のアニメーションをつけるコードスニペット

UIButtonのExtensionにアニメーションを追加してみました。

import UIKit

extension UIButton{
    
    /**
     * ボタン押下時のアニメーション
     */
    func pushAnimation() {
        
        let defaultButton = self.bounds
        
        UIView.animateWithDuration(1.5,
            delay: 0.0,
            usingSpringWithDamping: 0.2,
            initialSpringVelocity: 10,
            options: UIViewAnimationOptions.CurveEaseInOut,
            animations: { () -> Void in
                
                self.bounds = CGRectMake(
                    defaultButton.origin.x,
                    defaultButton.origin.x,
                    defaultButton.size.width + 40,
                    defaultButton.size.height)
                
            }) { (finished) -> Void in
                
                self.bounds = CGRectMake(
                    defaultButton.origin.x,
                    defaultButton.origin.x,
                    defaultButton.size.width,
                    defaultButton.size.height)
        }
    }
}

使い方

    @IBAction func tappedButton(sender: UIButton) {
        sender.pushAnimation()
    }