Ios 更改嵌入按钮的图像颜色(Swift3)

Ios 更改嵌入按钮的图像颜色(Swift3),ios,uiimageview,uibutton,swift3,mask,Ios,Uiimageview,Uibutton,Swift3,Mask,我可以使用以下代码将ui按钮的图像颜色从黑色更改为白色: extension UIImage { func maskWith(color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x:

我可以使用以下代码将
ui按钮的图像颜色从黑色更改为白色:

extension UIImage {
    func maskWith(color: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)

        let context = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(.normal)

        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        context.clip(to: rect, mask: cgImage!)

        color.setFill()
        context.fill(rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()!

        UIGraphicsEndImageContext()

    return newImage
    }
}
我正在使用以下方法设置
ui按钮的图像颜色:

//creditCardBtn is the the button variable
creditCardBtn.imageView?.image? = (creditCardBtn.imageView?.image?.maskWith(color: .white))!
我的问题 当用户将手指放在按钮上,然后缓慢地将手指拖开时,图像颜色会自行重置。我的想法是使用
@iAction
并在
内部进行润色时重置
ui按钮的图像。但是,这并没有阻止图像重置其颜色

以下是我尝试的代码:

@IBAction func creditCardTap(_ sender: UIButton) {
    creditCardBtn.imageView?.image?.maskWith(color: .white)
}
我在寻找什么:
如何防止按钮在UI活动中重置其颜色。

以下是一种更简单的方法,无需任何扩展,也无需在触摸时重置颜色:

let stencil = myImage.withRenderingMode(.alwaysTemplate) // use your UIImage here
myButton.setImage(stencil, for: .normal) // assign it to your UIButton
myButton.tintColor = UIColor.white // set a color

你能试试这个吗?它对我有用

let image = UIImage(named: "menu")
    let tintedImage = image?.withRenderingMode(.alwaysTemplate)
    mapMenuButton.setImage(tintedImage, for: .normal)
    mapMenuButton.tintColor = UIColor.appThemeColor()

swift 4和4.2

let img = UIImage.init(named: "buttonName")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
            btn.setImage(img, for: .normal)
            btn.tintColor = .gray

}

您是否尝试过在按钮上尝试其他动作事件?可能是触按、触按拖动退出或触按取消?我刚刚尝试了触按退出时结束、触按取消、触按下拉、触按拖动退出和触按内部。当用户有UI活动时,颜色仍在变化。+1用于使代码更加简单并消除扩展的需要,然后另一个+1用于提供解决方案,避免我在UI事件上重置颜色。非常感谢。
let img = UIImage.init(named: "buttonName")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
            btn.setImage(img, for: .normal)
            btn.tintColor = .gray

}