Ler Ws
Ler Ws

Reputation: 317

How to create a button which counts how many times it's being pressed and then activates a different function

How to create a button which counts how many user presses and then activate a different sound after a certain number of presses?

@IBAction func button(_ sender: UIButton) {
        var buttonCount: Int

        buttonAnim.startCanvasAnimation()
        let path = Bundle.main.path(forResource: "test", ofType:"wav")!
        let url = URL(fileURLWithPath: path)

        let path2 = Bundle.main.path(forResource: "stop-it", ofType:"mp3")!
        let url2 = URL(fileURLWithPath: path2)
        buttonCount = 0
        buttonCount = buttonCount + 1


        if buttonCount == 10 {

            do {
                let sound2 = try AVAudioPlayer(contentsOf: url2)
                bombSoundEffect2 = sound2
                sound2.play()
            } catch {
                // couldn't load file :(
            }

        }else{

            do {
                let sound = try AVAudioPlayer(contentsOf: url)
                bombSoundEffect = sound
                sound.play()
            } catch {
                // couldn't load file :(
            }
        }

    }

Here's my button code, I wish make it add on into an Int variable and when that variable reaches 5, it will reset itself and also play a different sound.

edit: I've edited the code, but it says there that the if portion will never be executed.

Upvotes: 0

Views: 151

Answers (2)

Siavash Alp
Siavash Alp

Reputation: 1452

    class ViewController: UIViewController {

@IBOutlet weak var dateLabelOutlet: UILabel!
var buttonCount: Int = 0
@IBAction func button(_ sender: UIButton) {

    buttonAnim.startCanvasAnimation()
    let path = Bundle.main.path(forResource: "test", ofType:"wav")!
    let url = URL(fileURLWithPath: path)

    let path2 = Bundle.main.path(forResource: "stop-it", ofType:"mp3")!
    let url2 = URL(fileURLWithPath: path2)
    buttonCount = buttonCount + 1


    if buttonCount == 10 {

        do {
            let sound2 = try AVAudioPlayer(contentsOf: url2)
            bombSoundEffect2 = sound2
            sound2.play()
        } catch {
            // couldn't load file :(
        }

    }else{

        do {
            let sound = try AVAudioPlayer(contentsOf: url)
            bombSoundEffect = sound
            sound.play()
        } catch {
            // couldn't load file :(
        }
    }

}

}

Upvotes: 0

Vikram Biwal
Vikram Biwal

Reputation: 2826

Declare var buttonCount = 0 out side of the function, and rest it in if condition.

Upvotes: 1

Related Questions