MILLEN BOX

音楽好きの組み込みソフトエンジニアによるプログラミング(主にiOSアプリ開発)の勉強の記録

Viewの点滅を繰り返す方法とその終了方法 [swift1.2] [animateWithDuration]

皆さんいかがお過ごしでしょうか。
本日はViewの点滅とその終了方法について。
起動後、Viewの点滅を繰り返させ、ボタンを押したらストップさせます。
Viewを点滅させるサンプルは、ネットにいっぱい上がっているのですが、
それの終了方法を言及しているモノが少なかったため、
私の備忘録代わりに残しておきます。

f:id:anthrgrnwrld:20150906085428g:plain

Githubは以下です。

GitHub - anthrgrnwrld/blinkApp

自分ポイント1

まずはViewの点滅のさせ方について。
それは animateWithDuration を使えば簡単にできます。
class func animateWithDuration(duration: NSTimeInterval, delay: NSTimeInterval, options: UIViewAnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)?) というメソッドを使います。
長くて難しそうですが、全然難しくありません。パラメーターを細分化するとこんな感じ。

  • duration: アニメーション時間
  • delay: アニメーションの開始を遅らせたい時間
  • options: アニメーションカーブや、繰り返しなんかを指定
  • animations: アニメーションさせたい処理を記載する (クロージャ)
  • completion: アニメーションを終了した時にして欲しい処理を記載する

今回は点滅を繰り返し実行したいので以下のように指定します。

  • duration: 1.0
  • delay: 0
  • options: UIViewAnimationOptions.Repeat (アニメーションを繰り返すoption)
  • animations: {self.blinkView.alpha = 0.0} (つまり透明度を100にする、0にする を繰り返すことで点滅を実現する)
  • completion: nil (今回は指定なし)
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var blinkView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //点滅アニメーション
        UIView.animateWithDuration(1.0, delay: 0.0,
            options: UIViewAnimationOptions.Repeat, animations: { () -> Void in
            self.blinkView.alpha = 0.0
            }, completion: nil)
        
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func pressButton(sender: AnyObject) {
        
       //点滅をStopする処理はココに(自分ポイント2にて)

    }


}

自分ポイント2

点滅をストップする方法。
ボタンを押した時に@IBAction内に点滅ストップ処理を記載すればよいです。
自分ポイント1で指定した方法の繰り返しアニメーションは、すごく楽に実装できるのですが、ちゃんとしたRepeatの終了方法がわからず苦労しました。
割と力技なのですが、ボタン押下時に他のアニメーション処理を実行することで停止させました。 (参考: ktyr report [コトヨリリポート] - [objective-c]animateWithDurationを途中で止める )

class ViewController: UIViewController {

    ...

    @IBAction func pressButton(sender: AnyObject) {

        //点滅の停止処理        
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.animateWithDuration(0.001, animations: {
            self.blinkView.alpha = 1.0
            })
    }


}

(追記)
点滅の終了方法として、以下の方法でも可能だよ〜とコメント頂きました!
@toshi58601414 さん、ありがとうございます!!

class ViewController: UIViewController {

    ...

    @IBAction func pressButton(sender: AnyObject) {

        //点滅の停止処理        
        //こっちの方法でもOK
        blinkView.layer.removeAllAnimations()
        blinkView.alpha = 1.0
    }


}

animateWithDurationはちょっとしたアニメーションの実行する場合、とても便利です。