如何在 Swift3 中更改一组按钮图像的颜色?



我最近在这里问了一个问题,我想了解如何改变button imageUIColor。我遵循了@Dorian罗伊的建议,非常干净,非常适合我的需求。虽然我之前的具体问题是围绕一个按钮,但我想知道如何更改多个UIBUttons。这能做到吗?我的想法是subclass一个UIButton并初始化它以自动更改其image颜色。不过,我不太明白该怎么做。

以下是我目前执行此操作的方式,我正在寻找更优雅的解决方案。

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
} 

最简单的方法是创建一个UIButton数组并遍历所有元素。

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
}

您还可以创建UIButtonextension,并将Button的此设置代码放入这样的函数中。

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

现在只需使用闭包forEach调用此函数。

buttonArray.forEach { button in
    button.setImageWithRandringMode()
}

最新更新