I have a UIBarButton in my navigation bar, I set an image (silhouette.png) to it from the storyboard, and I can change that image's tint (color) at will:
if let num2 = Int(s, radix: 16) { //s="00ff00"
flamingoBtn.tintColor = UIColor(netHex:num2) //this btn is an IBoutlet
}
However, at some point I change the original image for another image (icon.png), programmatically, so I don't need to change the tint in this case, so far so good:
if let url = NSURL(string: "http://www.123di.com/CanonSGLens_132.png") {
if let data = NSData(contentsOfURL: url) {
var newImgThumb : UIImage=UIImage(data: data)!
var iconBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
iconBtn.setImage(newImgThumb, forState: UIControlState.Normal)
iconBtn.addTarget(self, action: "goToSettings:", forControlEvents: UIControlEvents.TouchUpInside)
var item = UIBarButtonItem(customView: iconBtn)
self.navigationItem.leftBarButtonItem = item
print("CUSTOM ICON: DOWNLOADED")
}
}
The problem comes, when I switch to the icon image to the original silhouette.png, because I cannot modify the tint any longer, it remains always blue silhoute (default color), instead of green, red, etc:
var newImgThumb : UIImage=UIImage(named: "happyface.png")!
var replyBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
replyBtn.setImage(newImgThumb, forState: UIControlState.Normal)
replyBtn.addTarget(self, action: "goToSettings:", forControlEvents: UIControlEvents.TouchUpInside)
replyBtn.tintColor = UIColor.greenColor()
var item = UIBarButtonItem(customView: replyBtn)
item.tintColor = UIColor.greenColor()//UIColor(netHex:num2)
self.navigationItem.leftBarButtonItem = item
What am I doing wrong, why are tint changes igonred afterwards?? If you need extra details let me know.
If you google how to set the custom image for your bar button, pretty much everyone will tell you create a UIButton
and then create the UIBarButtonItem
from the UIButton
as a customView:
. In which case, you are doing the right thing here.
However, if you create the UIBarButtonItem
via cutomView:
, you are not able to change the tintColor
any more. And this following is how you set custom image and also changing the tintColor
let item = UIBarButtonItem.init(image: UIImage(named: "happyface.png")!,
style: .Plain,
target: self,
action: Selector("goToSettings:"))
item.tintColor = UIColor.greenColor()
self.navigationItem.leftBarButtonItem = item
Depending where are you calling the code above, you might need to put it inside this structure, to make it run in the UI thread and make the change visible:
dispatch_async(dispatch_get_main_queue()) {
//code here
}