LoginSignup
10
12

More than 5 years have passed since last update.

バウンドするボタンの作り方

Last updated at Posted at 2017-08-14

どーゆーヤツ?

こーゆーヤツです。

環境

・Xcode -> ver 8.3.3
・iOS -> ver 10.3.3

Swiftファイル側

3つのIBActionを用意します。

ViewController.swif
       @IBOutlet private weak var myButton: UIButton!

    /// ボタンを押したタイミングで呼ばれます。
    @IBAction func didTouchDownButton() {
        // ボタンを縮こませます 
        UIView.animate(withDuration: 0.2, animations: { _ in
            self.myButton.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        })
    }

    /// ボタンを押下途中で指から離れたタイミングで呼ばれます。
    /// NOTE: ボタンに指が触れたままボタン外の領域まで指を移動したままにするとボタンが縮こまったままになってしまうのを防ぐ処理です。
    @IBAction func didTouchDragExitButton() {
        // 縮こまったボタンをアニメーションで元のサイズに戻します
        UIView.animate(withDuration: 0.2, animations: { _ in
            self.myButton.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        })
    }

    /// ボタンが指から離れたタイミングで呼ばれます。
    @IBAction func didTouchUpInsideButton() {
        // バウンド処理です
        UIView.animate(withDuration: 0.5,
                       delay: 0.0,
                       usingSpringWithDamping: 0.3,
                       initialSpringVelocity: 8,
                       options: .curveEaseOut,
                       animations: { () -> Void in

            self.myButton.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        }, completion: nil)
    }

Storyboard側

2箇所いじります。

  1. myButton変数を対象ボタンまでアウトレット接続します。

  2. ボタンのIBAction処理を3つ繋げます。
    2-1. didTouchDragExitButton -> ボタンまで引っ張り「Touch Drag Exit」を指定
    2-2. didTouchDownButton -> ボタンまで引っ張り「Touch Down」を指定
    2-3. didTouchUpInsideButton -> ボタンまで引っ張り「Touch Up Inside」を指定
    ※ IBActionは同部品に複数設定できます

あああ.png

まとめ

・IBActionを使ってアニメーション処理を実施する処理を書いてみました。
・同画面に複数ボタンがあり、同じような処理をさせたい時には各ボタンにtag値を設定し、その値でアニメーション処理したいボタンを選定するなんてこともしてます。
・もっと便利なStoryboard上の部品のアニメーション処理をご存知であれば教えてください。

以上です。

10
12
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
10
12