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

Changing color of image embedded to a button (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
    }
}

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

//creditCardBtn is the the button variable
creditCardBtn.imageView?.image? = (creditCardBtn.imageView?.image?.maskWith(color: .white))!

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

这是我试过的代码:

@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
  //works in func tableView(_ tableView: UITableView, cellForRowAt IndexPath: IndexPath) -> UITableViewCell

if redButton == true {
        let stencil = UIImage(named: "phoneCircle.png")?.withRenderingMode(.alwaysTemplate)
        cell.patientCTCallButton.setImage(stencil, for: .normal)
        cell.patientCTCallButton.tintColor = .red // 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

}