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

Sam*_*ami 2 mask uibutton uiimageview ios swift3

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在UIButton使用以下设置图像的颜色:

//creditCardBtn is the the button variable
creditCardBtn.imageView?.image? = (creditCardBtn.imageView?.image?.maskWith(color: .white))!
Run Code Online (Sandbox Code Playgroud)

我的问题 当用户将手指放在按钮上然后慢慢地将手指拖开时,图像颜色会自行重置.我的想法是当有一个时使用@IBAction并重置UIButton图像Touch Up Inside.但是,这并不能阻止图像重置其颜色.

这是我试过的代码:

@IBAction func creditCardTap(_ sender: UIButton) {
    creditCardBtn.imageView?.image?.maskWith(color: .white)
}
Run Code Online (Sandbox Code Playgroud)

我在寻找: 如何防止按钮从UI活动重置其颜色.

Dor*_*Roy 7

这是一种更简单的方法,无需任何扩展即可完成此操作,无需重置触摸颜色:

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
Run Code Online (Sandbox Code Playgroud)