How do I programmatically remove images of UIButtons that have tags?

I have nine buttons that are each linked to a single IBAction. They all have tags (1,2,3 etc.) and I want to be able to click a button and remove all of the buttons' images.


I currently have:


@IBOutlet weak var buttonsWithImages: UIButton!

@IBAction func removeImages(_ sender: AnyObject) {
self.buttonsWithImages.setImage(nil, for: .normal)
}

Please try to describe what you really want to achieve and what is the difficulty you are currently experiencing.


Please explain why this cannot be a solution for you:

    @IBOutlet weak var button1WithImages: UIButton!
    @IBOutlet weak var button2WithImages: UIButton!
    @IBOutlet weak var button3WithImages: UIButton!
    @IBOutlet weak var button4WithImages: UIButton!
    @IBOutlet weak var button5WithImages: UIButton!
    @IBOutlet weak var button6WithImages: UIButton!
    @IBOutlet weak var button7WithImages: UIButton!
    @IBOutlet weak var button8WithImages: UIButton!
    @IBOutlet weak var button9WithImages: UIButton!

    @IBAction func removeImages(_ sender: AnyObject) {
        self.button1WithImages.setImage(nil, for: .normal)
        self.button2WithImages.setImage(nil, for: .normal)
        self.button3WithImages.setImage(nil, for: .normal)
        self.button4WithImages.setImage(nil, for: .normal)
        self.button5WithImages.setImage(nil, for: .normal)
        self.button6WithImages.setImage(nil, for: .normal)
        self.button7WithImages.setImage(nil, for: .normal)
        self.button8WithImages.setImage(nil, for: .normal)
        self.button9WithImages.setImage(nil, for: .normal)
    }

You could create an IBOutlets collection to have them in an array and so have a loop to remove all the images as you did for a single one.


    @IBOutlet weak var buttonsWithImages: [UIButton]!


Connect each button to this IBOutlet

Connect each button to the same IBAction


@IBAction func removeImages(_ sender: AnyObject) {
     for button in buttonsWithImages {
       button.setImage(nil, for: .normal)
  }
}
How do I programmatically remove images of UIButtons that have tags?
 
 
Q