9
6

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 3 years have passed since last update.

【Swift5】Timerでスライドショー機能を実装(初心者向け)

Last updated at Posted at 2020-07-17

背景

Timerを使ったアプリの質問をよく受けるので、スライドショーを例に実装を書いてみた。

プロジェクトのソース

念のためプロジェクトをGithubに上げてあるので
よかったらどうぞ!
https://github.com/tomoki-inoue1221/slideShowApp

画面・機能

実装画面

画像と再生ボタンだけを用意
Simulator Screen Shot - iPhone SE (2nd generation) - 2020-07-17 at 23.05.10.png

機能

  • 再生ボタンを押すと、1秒ごとに画像が切り替わる(スライドショー機能)
  • スライドショー中はボタンの名前を「停止」に切り替える(ボタンひとつで再生・停止の機能)

実装

実装手順

  1. assetsにスライドショーさせたい画像を配置
  2. storyboardでautoLayoutの設定
  3. storyboardからIBOutletとボタンのアクションを接続
  4. コードを実装

コード

ViewController.swift
import UIKit

class ViewController: UIViewController {
    
    // outletの接続
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var imageView: UIImageView!
    
    // 配列に指定するindex番号を宣言
    var nowIndex:Int = 0
    
    // スライドショーに使用するタイマーを宣言
    var timer: Timer!
    
    // スライドショーさせる画像の配列を宣言
    var imageArray:[UIImage] = [
        UIImage(named: "neko1")!,
        UIImage(named: "neko2")!,
        UIImage(named: "neko3")!,
        UIImage(named: "neko4")!,
        UIImage(named: "neko5")!
    ]
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    // 再生ボタンを押した時の処理
    @IBAction func slideShowButton(_ sender: Any) {
        // 再生中か停止しているかを判定
        if (timer == nil) {
            // 再生時の処理を実装
            
            // タイマーをセットする
            timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(changeImage), userInfo: nil, repeats: true)
            
            // ボタンの名前を停止に変える
            startButton.setTitle("停止", for: .normal)
            
        } else {
            // 停止時の処理を実装
            // タイマーを停止する
            timer.invalidate()
            
            // タイマーを削除しておく(timer.invalidateだけだとtimerがnilにならないため)
            timer = nil
            
            // ボタンの名前を再生に直しておく
            startButton.setTitle("停止", for: .normal)
        }
    }
    
    @objc func changeImage() {
        // indexを増やして表示する画像を切り替える
        nowIndex += 1
        
        // indexが表示予定の画像の数と同じ場合
        if (nowIndex == imageArray.count) {
            // indexを一番最初の数字に戻す
            nowIndex = 0
        }
        // indexの画像をstoryboardの画像にセットする
        imageView.image = imageArray[nowIndex]
    }
}

補足

  1. タイマー停止時にtimer = nilにしている理由

timer.invalidate()でtimerは停止するが、timerに停止中という状態がないので
timerをnilにして、nilかどうかで判定を行っている

  1. タイマーで呼び出す関数が@objcがついてる理由

https://qiita.com/masakihori/items/4a715f28fc7f18d1a625
こちらの記事を参照ください

9
6
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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?