cs4alhaider
cs4alhaider

Reputation: 1446

Array with images name to change my image every time i press the button in Swift

I have an array with image names let arrowArray = ["up","down","right","left"] and I placed an imageView and a button with an action in my storyboard

I want to change my image every time i press the button, Can any one help me ?

Upvotes: 0

Views: 331

Answers (2)

cs4alhaider
cs4alhaider

Reputation: 1446

Thanks to Xcoder for the previous answer, i have fix the code so the image won't stop

func updateImage() {

    if arrowIndex >= 0 && arrowIndex < 4 {
        arrowImage.image = UIImage(named: arrowArray[arrowIndex])
        arrowIndex += 1
        if arrowIndex == 4 {
            arrowIndex = 0
        }
    }else{
        arrowIndex = 0
    }

}


@IBAction func buttonClicked(_ sender: UIButton) {

   updateImage() 

      }

Upvotes: 0

Xcoder
Xcoder

Reputation: 1453

In your view controller:

var arrowIndex: Int = 0

@IBAction func buttonClicked(_ sender: UIButton) {
    yourImageView.image = UIImage(named: arrowArray[arrowIndex])
    arrowIndex += 1

    if arrayIndex == (arrowArray.count - 1) {
        arrayIndex = 0
    }    
}

This will display the up arrow first. You can change arrowIndex's initial value to display different arrows first.

Upvotes: 3

Related Questions