35
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでUIButtonのタップ時に押された感のアニメーション

Last updated at Posted at 2015-01-08

タップしたかどうかはtouchesBeganなどを使います。

下記はtouchesBeganした時に、
「ボタンがわずかに縮小し、alphaが若干薄くなる」
というUIButtonを継承したクラスを作ってみました。

import UIKit

class UIButtonAnimated: UIButton {
    
    override init() {
        super.init()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        super.touchesBegan(touches, withEvent: event)
        self.touchStartAnimation()
    }
    
    override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
        super.touchesCancelled(touches, withEvent: event)
        self.touchEndAnimation()
    }
    
    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        super.touchesEnded(touches, withEvent: event)
        self.touchEndAnimation()
    }

    private func touchStartAnimation(){
        UIView.animateWithDuration(0.1,
            delay: 0.0,
            options: UIViewAnimationOptions.CurveEaseIn,
            animations: {() -> Void in
                self.transform = CGAffineTransformMakeScale(0.95, 0.95);
                self.alpha = 0.7
            },
            completion: nil
        )
    }
    private func touchEndAnimation(){
        UIView.animateWithDuration(0.1,
            delay: 0.0,
            options: UIViewAnimationOptions.CurveEaseIn,
            animations: {() -> Void in
                self.transform = CGAffineTransformMakeScale(1.0, 1.0);
                self.alpha = 1
            },
            completion: nil
        )
    }

}

利用するときは普通のUIButtonと同じく

let btn = UIButtonAnimated(frame: CGRectMake(0, 0, 100, 100))

という感じで使えばOKです。

35
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?