改变embedded到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))! 

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

这是我试过的代码:

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

我在找什么:如何防止button重置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 } 

白色的“phoneCircle.png”以红色标出 在这里输入图像说明

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

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