0

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 ?

1
  • Please specify how you want to change the image. Do you want to iterate through the array and once it reaches the last element, start again from the first? Or once the last element is reached, stop changing the picture. Or just choose a random element from the array each time the button is pushed. Please be more specific. Commented Jan 14, 2018 at 17:11

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I got a crash ! Index out of range
@desperado_ah Sorry about that. Check my updated answer, and let me know if it works for you.
0

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() } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.