Reputation: 519
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:
I hope my questions are clear. Please let me know if they are not. Help is much appreciated!
Upvotes: 0
Views: 916
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