2016-12-27 119 views
1

我能夠從黑UIButton的圖像的顏色改變爲白色用下面的代碼:改變顏色嵌入到一個按鈕(Swift3)

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活動重置它的顏色。

+0

您是否嘗試過使用按鈕上的其他操作事件?也許觸摸下,觸摸拖動退出或觸摸取消? – ThePringle

+0

我剛剛嘗試過'在退出時完成,'取消觸摸','向下觸摸','觸摸拖動退出'和'向上觸摸內部'。當用戶進行UI活動時,顏色仍然在變化。 – Sami

回答

5

這裏是這樣做沒有任何擴展,而無需觸摸重置顏色更簡單的方法:

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 
+0

+1使代碼更加簡單,無需擴展,然後再提供一個解決方案,避免我必須重置UI事件的顏色。謝謝 – Sami

0
//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 
} 

white "phoneCircle.png" before colored red enter image description here

0

你可以試試這個它是爲我工作。

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