codeDude
codeDude

Reputation: 519

how to change image of one button by pressing other buttons?

On a viewcontroller I have 101 buttons. If one of the first 100 buttons is pressed, I want to change the image of button number 101 ( I have 100 images in this project; image1,image2,image3 etc.)

So I have done this by giving every button a tag from 0-100 and then make a switch statement based on sender.tag

@IBOutlet weak var button101 : UIButton!

var i = 1

  // I hooked up all the other 100 buttons to a single IBAction
  @IBAction func buttonTapped(sender: UIButton) {

 switch sender.tag {

case 0:  i = 1

  let image = UIImage (named: "image\(i)")
  button101.setImage(image, forState:.Normal)

case 1:   i = 2

  let image = UIImage (named: "image\(i)")
  button101.setImage(image, forState:.Normal)

case 2:   i = 3

 let image = UIImage (named: "image\(i)")
  button101.setImage(image, forState:.Normal)

case ..: // etc. until case 99 (because button 100 has tag 99)

default: break

This super ugly code works: It changes the image of button number 101 into the specified image(i). But I want a more elegant and better solution.

I have 2 questions:

  1. How to initialise the 'image' constant/variable in a better way (outside the IBAction)?
  2. What kind of (loop)statement to use instead of this large switch statement? So: I want to determine which button is pressed, then update the value of var i, loop through the images and find and update the image of button101 with the image(i).

I hope my questions are clear. Please let me know if they are not. Help is much appreciated!

Upvotes: 0

Views: 916

Answers (1)

Caleb
Caleb

Reputation: 5616

Your switch statement acts the same as:

if sender.tag < 100 {
    let image = UIImage (named: "image\(sender.tag + 1)")
    button101.setImage(image, forState:.Normal)
}

You can put your UIImage at the top of your ViewController with var UIImage: UIImage! if you want to, but I do not see any reason to do this.

Upvotes: 1

Related Questions