繁体   English   中英

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

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

我最近在这里问了一个问题, 这里我想了解如何更改button imageUIColor 我遵循@Dorian Roy的建议,该建议非常干净,非常适合我的需求。 虽然我之前的具体问题是围绕一个按钮,但我想知道如何更改多个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
}

您还可以创建UIButton extension ,并将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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM