公開中のアプリ

[Swift/Xcode]初心者必見!iOSアプリ作成から公開まで徹底解説!#11「アニメーション編③」

今回は、ボタンを離したら色が元に戻ってしまうところを修正したいと思います!

動作環境は下記の通りです!
Xcode Version 12.5 Swift version 5.4

アニメーションの完成動画はこちらです!

実装の流れ

今まではボタンを離したら色を元に戻していましたが、
2秒以上押された時はボタンの色を青のままになるように実装し直します。

①Bool型の変数をfalseで作っておいて、2秒以上押されたらtrueになるようにする。

②longPressedメソッドのif文のelse ifの時に、「2秒経過したか or してないか」で条件分岐する。

こんなイメージでしょうか?
とりあえずやってみましょう!

longPressedメソッドの修正

実装の流れを元に修正したコードが下記です。

//タイマー初期化
var timer: Timer!
var longTapOK = false

//長押し機能
@objc func longPressed(_ sender: UILongPressGestureRecognizer) {

    if sender.state == .began {
        print("長押し開始")
        UIView.animate(withDuration: 2) {
            self.buttonArray[sender.view!.tag - 1].backgroundColor = UIColor.blue
        }
        startTimer()

    } else if sender.state == .ended {
        print("長押し終了")
        if longTapOK == false {
            UIView.animate(withDuration: 0.1) {
                self.buttonArray[sender.view!.tag - 1].backgroundColor = UIColor.lightGray
            }
            timer.invalidate()
        } else {
            print("ロングタップ成功")
            longTapOK = false
        }
    }
}

//タイマーの設定
func startTimer() {
    timer = Timer.scheduledTimer(
        timeInterval: 2, //タイマーの間隔を設定
        target: self,
        selector: #selector(self.timerCounter), //メソッドの設定
        userInfo: nil,
        repeats: false) //リピートするかどうか
}
    
//タイマーで実行される処理
@objc func timerCounter() {
    longTapOK = true
    animateView(topViewInner)
    AudioServicesPlaySystemSound(1102)
   }

3行目が2秒経過した時に使うBool型の変数です。

長押し認識されると13行目のstartTimer()が実行されます。
startTimer()が実行されると、2秒後に34行目のtimerCounterが実行されます。
timerCounterでBool型の変数「longTapOK」をtrueに変更、
さらに「ぽよよんアニメーション」とバイブを実行してます。

変数longTapOKがtrueに変更されたので、17行目のif文がelseに流れて、
ボタンの色が元に戻らない(グレイにならない)ようにしています。
そして、「longTapOK」をfalseに戻しておきます。

ここまでで一度ビルドしてみましょう!
多分、色は元に戻らず青色のままで成功したと思います!

これでOKかと思いきや、貯金額とか表示するラベルが反応しなくなっちゃいました!!

ラベルが更新されない問題の解決

なんでかな〜っと思って原因を調べてみるとすぐ判明しました!

今まではボタンをタップした時にラベルを更新していましたね??
そう言えば前回の記事で、タップした時の機能は必要なくなって消しちゃったのでラベルが更新されないのは当然ですね(^^;

じゃ復活させれば良いかと言うとそう言う訳でもなくて、長押し機能とタップは同時には実行できないので、別の方法で実装する必要があります。


ラベルを更新する関数を作ってあげて、2秒後にラベルを更新してあげれば解決しそうです!

コードは下記です!

//タイマー初期化
var timer: Timer!
//2秒長押ししたかどうか判定する変数
var longTapOK = false
//ボタンのタグを関数の外に出す為の変数
var btnTag = 0

//長押し機能
@objc func longPressed(_ sender: UILongPressGestureRecognizer) {

    if sender.state == .began {
        print("長押し開始")
        btnTag = sender.view!.tag
        UIView.animate(withDuration: 2) {
            self.buttonArray[sender.view!.tag - 1].backgroundColor = UIColor.blue
        }
        startTimer()

    } else if sender.state == .ended {
        print("長押し終了")
        if longTapOK == false {
            UIView.animate(withDuration: 0.1) {
                self.buttonArray[sender.view!.tag - 1].backgroundColor = UIColor.lightGray
            }
            timer.invalidate()
        } else {
            print("ロングタップ成功")
            longTapOK = false
        }
    }
}

//タイマーの設定
func startTimer() {
    timer = Timer.scheduledTimer(
        timeInterval: 2, //タイマーの間隔を設定
        target: self,
        selector: #selector(self.timerCounter), //メソッドの設定
        userInfo: nil,
        repeats: false) //リピートするかどうか
}
    
//タイマーで実行される処理
@objc func timerCounter() {
    longTapOK = true
    animateView(topViewInner)
    AudioServicesPlaySystemSound(1102)
    updateLabel()
}
    
//ラベルの値を更新する(長押し認識してから2秒後に実行される)
func updateLabel() {
    //貯金額を更新
    totalSavings += btnTag
    //合計日数を更新
    whatDay += 1
    //貯金額ラベルを更新
    moneyLabel.text = "合計貯金額\(totalSavings)円"
    //合計日数ラベルを更新
    dayLabel.text = "\(whatDay)日目"
}
    
//ぽよよんアニメーション
func animateView(_ viewToAnimate:UIView) {
    UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
        viewToAnimate.transform = CGAffineTransform(scaleX: 1.08, y: 1.08)
    }) { (_) in
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 10, options: .curveEaseOut, animations: {
            viewToAnimate.transform = .identity

        }, completion: nil)
    }
}

まずは52行目ですね!
これが新しく作ったupdateLabel()関数です!!

ここがちょっとややこしめポイントなので詳しく説明したいと思います!


updateLabel()では、貯金額合計と合計日数のラベルを更新する処理を書いています。

54行目の変数totalSavingsは貯金額の合計を保持する為の変数なので、押したボタンのタグ番号をそのまま足せばOKです!

なので、前回同様「sender.view!.tag」「sender.tag」とかでボタンのタグ番号を取得しようとしましたがエラーになりました。

このあたり、僕もまだまだ勉強不足なのですが、
ボタン生成時に機能として追加したメソッド(今回ならlongPressedメソッド)の中じゃないと取得できないのかなって思いました。

なので、タグ番号を格納する変数を一つ用意して、
longPressedメソッドの中でタグ番号を取得してその変数に格納する方法を使います。

このあたり良い方法があれば教えて欲しいです!!


コードで言うと、
6行目がタグ番号を格納する変数btnTagです。

13行目でタグ番号を変数btnTagに代入してます。

そして54行目で変数totalSavingsに変数btnTagを足してます!

まとめ

もしかしたら今後、色々問題が出て来るかもしれませんが一応今回でアニメーション部分は完成です!

個人的にはアニメーション部分はもっと複雑になるかなって思ってましたが意外とすんなりいけました!

次ですが今のままではアプリを立ち上げ直した時に
押したボタンとか貯金額とか元に戻っちゃうと思います!
そうならないようにデータを保持できるようにしたいと思います!

ここまで読んでくれた人ありがとうございます!
コメントお待ちしております!

ここまでのコード全部!

import UIKit
import AudioToolbox

class MainViewController: UIViewController {

//スクロールビュー
let scrollView = UIScrollView()
//ボタンを表示用のビュー
let inView: UIView = UIView()
//スタックビュー縦用
var stackV: UIStackView = UIStackView()
//ボタンの配列
var buttonArray: [UIButton] = []
//スタックビュー横を格納する為の配列
var stkArray: [UIStackView] = []
//貯金額合計
var totalSavings = 0
//貯金開始?日目
var whatDay = 0
// ボタンを用意
var addBtn: UIBarButtonItem!

//オレンジ色のビュー
let topView: UIView = UIView()
//白色のビュー
let topViewInner: UIView = UIView()
//合計日数のラベル
let dayLabel: UILabel = UILabel()
//貯金額のラベル
let moneyLabel: UILabel = UILabel()


override func viewDidLoad() {
    super.viewDidLoad()
    //ビューの生成
    viewCreate()
    //ラベルの生成
    labelCreate()
    //ボタンの生成
    btnCreate()
    //スタックビューの生成
    stackViewCreate()

    //ナビゲーションコントローラーまわり
    //タイトル
    self.title = "365貯金"
    //背景色
    self.navigationController?.navigationBar.barTintColor = UIColor.orange
    //セーフエリアとの境目の線を消す
    self.navigationController?.navigationBar.shadowImage = UIImage()
    //上部が黒くなるのを回避
    view.backgroundColor = UIColor.systemBackground
}


//ビュー生成
func viewCreate() {
    //オレンジ色のビューの表示
    view.addSubview(topView)
    //白色のビューの表示
    topView.addSubview(topViewInner)
    //スクロールビューの表示
    view.addSubview(scrollView)
    //ボタン表示用ビューの表示
    scrollView.addSubview(inView)

    //スクロールビューの設定
    //AutosizingをAutoLayoutに変換しないようにしている(おまじない)
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    //スクロールビューの上側の位置を設定
    scrollView.topAnchor.constraint(equalTo: topView.bottomAnchor, constant: 20.0).isActive = true
    //スクロールビューの下側の位置を設定
    scrollView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -20.0).isActive = true
    //Y軸
    scrollView.centerXAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor).isActive = true
    //横幅
    scrollView.widthAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.widthAnchor, multiplier: 0.9).isActive = true


    //ボタン表示用ビューの設定
    //AutosizingをAutoLayoutに変換しないようにしている(おまじない)
    inView.translatesAutoresizingMaskIntoConstraints = false
    //横幅
    inView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0).isActive = true
    //この4つの制約をつけて初めてスクロールするっぽい
    inView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 0).isActive = true
    inView.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: 0.0).isActive = true
    inView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0.0).isActive = true
    inView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0.0).isActive = true


    //オレンジのビューのレイアウト
    //AutosizingをAutoLayoutに変換しないようにしている(おまじない)
    topView.translatesAutoresizingMaskIntoConstraints = false
    //X軸
    topView.centerXAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor).isActive = true
    //Y軸
    topView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
    //横幅
    topView.widthAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.widthAnchor, multiplier: 1).isActive = true
    //縦幅
    topView.heightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.heightAnchor, multiplier: 0.125).isActive = true
    //背景色
    topView.backgroundColor = UIColor.orange

    //白色のビューのレイアウト
    //(おまじない)
    topViewInner.translatesAutoresizingMaskIntoConstraints = false
    //X軸
    topViewInner.centerXAnchor.constraint(equalTo: topView.centerXAnchor).isActive = true
    //Y軸
    topViewInner.centerYAnchor.constraint(equalTo: topView.centerYAnchor).isActive = true
    //横幅
    topViewInner.widthAnchor.constraint(equalTo: topView.widthAnchor, multiplier: 0.9).isActive = true
    //縦幅
    topViewInner.heightAnchor.constraint(equalTo: topView.heightAnchor, multiplier: 0.75).isActive = true
    //背景色
    topViewInner.backgroundColor = UIColor.white
    }

//ラベル生成
func labelCreate() {
    //合計日数のラベルを表示
    topViewInner.addSubview(dayLabel)
    //貯金額のラベルを表示
    topViewInner.addSubview(moneyLabel)

    //合計日数のラベルのレイアウト
    //(おまじない)
    dayLabel.translatesAutoresizingMaskIntoConstraints = false
    //X軸
    dayLabel.leftAnchor.constraint(equalTo: topViewInner.leftAnchor, constant: 20.0).isActive = true
    //Y軸
    dayLabel.centerYAnchor.constraint(equalTo: topViewInner.centerYAnchor).isActive = true
    //ラベルのテキスト
    dayLabel.text = "\(whatDay)日目"

    //貯金額のラベルのレイアウト
    //(おまじない)
    moneyLabel.translatesAutoresizingMaskIntoConstraints = false
    //X軸
    moneyLabel.rightAnchor.constraint(equalTo: topViewInner.rightAnchor, constant: -20.0).isActive = true
    //Y軸
    moneyLabel.centerYAnchor.constraint(equalTo: topViewInner.centerYAnchor).isActive = true
    //ラベルのテキスト
    moneyLabel.text = "合計貯金額 \(totalSavings)円"
}
    
//スタックビュー生成
func stackViewCreate() {
    //スタックビュー縦の設定
    //スタックビューの方向を縦に
    stackV.axis = .vertical
    //中のオブジェクトをどこに揃えて配置するか
    stackV.alignment = .fill
    //どう配置するか
    stackV.distribution = .fill
    //オブジェクト同士のスペース
    stackV.spacing = 4
    //おまじない
    stackV.translatesAutoresizingMaskIntoConstraints = false
    //stackVの背景色
    stackV.backgroundColor = UIColor.white
    //stackVを表示
    inView.addSubview(stackV)
    //X軸
    stackV.centerXAnchor.constraint(equalTo: inView.centerXAnchor).isActive = true
    //トップ位置
    stackV.topAnchor.constraint(equalTo: stackV.topAnchor, constant: 0.0).isActive = true
    //横幅
    stackV.widthAnchor.constraint(equalTo: inView.widthAnchor, multiplier: 1.0).isActive = true
    //縦幅
    stackV.heightAnchor.constraint(equalTo: inView.heightAnchor, multiplier: 1.0).isActive = true

    //スタックビュー横を自動生成
    for i in 0 ..< 73 {
        //StackHの生成
        let stackH:UIStackView = UIStackView()
        //スタックビューの方向を横に
        stackH.axis = .horizontal
        //オブジェクト同士のスペース
        stackH.spacing = 4
        //中のオブジェクトをどこに揃えて配置するか
        stackH.alignment = .fill
        //どう配置するか
        stackH.distribution = .fillEqually
        //スタックビュー配列に追加
        stkArray.append(stackH)
        //stackVの中にstackHを格納
        stackV.addArrangedSubview(stkArray[i])
    }

    //ボタンの配置
    //for文のカウンター変数
    var count = 0
    //for文で365個のボタンをどのstackHに入れるか決めている
    for i in 1 ..< 366 {
        //カウントの数に応じてどのstackHに入るか決定する。
        stkArray[count].addArrangedSubview(buttonArray[i - 1] as UIView)
        //ボタンは5列なので5の倍数でcountを一つ増やす。
        if i % 5 == 0 {
            count += 1
        }
    }
}

//ボタン生成
func btnCreate() {
    //ボタンの生成と設定
    //ボタンにtagを付ける為の変数
    var tagNumber = 1
    //for文でボタンを生成
    for _ in 0...364 {
        //ボタン生成
        let button: UIButton = UIButton(type: .custom)
        //タイトルの色
        button.setTitleColor(UIColor.black, for: UIControl.State())
        //タイトルは数字なのでtagナンバーを指定
        button.setTitle(String(tagNumber), for: UIControl.State())
        //tag設定
        button.tag = tagNumber
        //背景色
        button.backgroundColor = UIColor.lightGray
        //ボーダーの横幅
        button.layer.borderWidth = 3
        //ボターの色
        button.layer.borderColor = UIColor.black.cgColor
        //AutosizingをAutoLayoutに変換しないようにしている(おまじない)
        button.translatesAutoresizingMaskIntoConstraints = false
        //ボタンの横幅が可変なのでボタンの高さは横幅と同じ長さを指定する事で正方形にしてる。
        button.heightAnchor.constraint(equalTo: button.widthAnchor, multiplier: 1.0).isActive = true
        //変数tagNumberに1追加
        tagNumber += 1
        //ボタン長押し
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(_:))
        )
        //長押しを認識する時間の設定
        longPressGesture.minimumPressDuration = 0.01
        //ボタンに長押し機能を付ける
        button.addGestureRecognizer(longPressGesture)
        //ボタンの配列に追加
        buttonArray.append(button)
    }
}

// MARK: - ここからアニメーション関係
//タイマー初期化
var timer: Timer!
//2秒長押ししたかどうか判定する変数
var longTapOK = false
//ボタンのタグを関数の外に出す為の変数
var btnTag = 0

//長押し機能
@objc func longPressed(_ sender: UILongPressGestureRecognizer) {

    if sender.state == .began {
        print("長押し開始")
        btnTag = sender.view!.tag
        UIView.animate(withDuration: 2) {
            self.buttonArray[sender.view!.tag - 1].backgroundColor = UIColor.blue
        }
        startTimer()

    } else if sender.state == .ended {
        print("長押し終了")
        if longTapOK == false {
            UIView.animate(withDuration: 0.1) {
                self.buttonArray[sender.view!.tag - 1].backgroundColor = UIColor.lightGray
            }
            timer.invalidate()
        } else {
            print("ロングタップ成功")
            longTapOK = false
        }
    }
}

//タイマーの設定
func startTimer() {
    timer = Timer.scheduledTimer(
        timeInterval: 2, //タイマーの間隔を設定
        target: self,
        selector: #selector(self.timerCounter), //メソッドの設定
        userInfo: nil,
        repeats: false) //リピートするかどうか
}
    
//タイマーで実行される処理
@objc func timerCounter() {
    longTapOK = true
    animateView(topViewInner)
    AudioServicesPlaySystemSound(1102)
    updateLabel()
}
    
//ラベルの値を更新する(長押し認識してから2秒後に実行される)
func updateLabel() {
    //貯金額を更新
    totalSavings += btnTag
    //合計日数を更新
    whatDay += 1
    //貯金額ラベルを更新
    moneyLabel.text = "合計貯金額\(totalSavings)円"
    //合計日数ラベルを更新
    dayLabel.text = "\(whatDay)日目"
}
    
//ぽよよんアニメーション
func animateView(_ viewToAnimate:UIView) {
    UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
        viewToAnimate.transform = CGAffineTransform(scaleX: 1.08, y: 1.08)
    }) { (_) in
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 10, options: .curveEaseOut, animations: {
            viewToAnimate.transform = .identity

        }, completion: nil)
    }
}
    
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

アプリ