Sami
Sami

Reputation: 587

How can I change a group of button's image's colors in Swift3?

I recently asked a question here where I wanted to understand how to change the UIColor of a button's image. I followed @Dorian Roy's recommendation which was very clean and it worked well for my needs. While my specific question previously was around a single button, I would like to know how to change multiple UIBUttons. Can this be done? My thought would be to subclass a UIButton and initialize it to automatically change its image color. I can't quite grasp how to do this though.

Here is how I am currently performing this action and I am seeking a more elegant solution.

private func changeBtnColors() {
    let ccStencil = creditCardBtn.imageView?.image?.withRenderingMode(.alwaysTemplate)
    let planeStencil = planeBtn.imageView?.image?.withRenderingMode(.alwaysTemplate)
    let towelStencil = towelBtn.imageView?.image?.withRenderingMode(.alwaysTemplate)
    let carStencil = carBtn.imageView?.image?.withRenderingMode(.alwaysTemplate)
    let trainStencil = trainBtn.imageView?.image?.withRenderingMode(.alwaysTemplate)
    let graphStencil = graphBtn.imageView?.image?.withRenderingMode(.alwaysTemplate)

    creditCardBtn.setImage(ccStencil, for: .normal)
    planeBtn.setImage(planeStencil, for: .normal)
    towelBtn.setImage(towelStencil, for: .normal)
    carBtn.setImage(carStencil, for: .normal)
    trainBtn.setImage(trainStencil, for: .normal)
    graphBtn.setImage(graphStencil, for: .normal)

    creditCardBtn.tintColor = UIColor.white
    planeBtn.tintColor = UIColor.white
    towelBtn.tintColor = UIColor.white
    carBtn.tintColor = UIColor.white
    trainBtn.tintColor = UIColor.white
    graphBtn.tintColor = UIColor.white
} 

Upvotes: 0

Views: 281

Answers (1)

Nirav D
Nirav D

Reputation: 72420

The simplest way is create one array of UIButton and loop through all the elements.

let buttonArray = [creditCardBtn, planeBtn, towelBtn, carBtn, trainBtn, graphBtn]
buttonArray.forEach { button in
    let image = button.imageView?.image?.withRenderingMode(.alwaysTemplate)
    button.setImage(image, for: .normal)
    button.tintColor = UIColor.white
}

You can also create extension of UIButton and put this settings code of Button in a function like this.

extension UIButton {
    func setImageWithRandringMode() {
        let image = self.imageView?.image?.withRenderingMode(.alwaysTemplate)
        self.setImage(image, for: .normal)
        self.tintColor = .white
    }
}

And now simply call this function with forEach closure.

buttonArray.forEach { button in

    button.setImageWithRandringMode()
}

Upvotes: 3

Related Questions