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

标签 ios uiimageview uibutton swift3 rendering

我最近问了一个问题here我想了解如何更改 buttonimageUIColor。我遵循了@Dorian Roy 的建议,该建议非常干净并且非常适合我的需要。虽然我之前的具体问题是围绕单个按钮,但我想知道如何更改多个 UIBUttons。这可以做到吗?我的想法是子类 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()
}

关于ios - 如何在 Swift3 中更改一组按钮图像的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41477792/

相关文章:

iphone - uialertview 不执行任何操作

ios - 在 UIScrollView 内旋转 UIImageView 问题

ios - 从 xib 加载的 UIView 中的 UIButton 在单击时根本不调用选择器

ios - 转换后的 tableview 图像产生 "unexpectedly found nil while unwrapping optional"

iphone - 轻松懒加载

添加 subview 后 iOS UIButton 文本颜色不会改变

ios - UIButton 释放问题

ios - 以编程方式获取 segue(和目标 View Controller )的任何方法?

ios - 核心数据 - NSFetchedResultController 按其他表字段对数据进行排序

ios - 运行今日扩展时的调试信息