snapchatdotcom snapchatdotcom - 4 months ago 15
Swift Question

How to set the color of the image view in UIButton on type Custom?

I've tried everything and nothing is happening. It just stays black. Am I missing something? I tried using the UIButton's image view but it doesn't make a change.

lazy var addFriendButton: UIButton = {
self.friendButton = UIButton(type: .Custom)

self.friendButton.bounds = CGRectMake(0, 0, 120, 80)
self.friendButton.backgroundColor = UIColor.redColor()
self.friendButton.translatesAutoresizingMaskIntoConstraints = false
self.friendButton.setTitle("Add Friend", forState: .Normal)
self.friendButton.titleLabel?.font = UIFont(name: "HelveticaNeue", size: 12)
self.friendButton.addTarget(self, action: #selector(addFriend), forControlEvents: .TouchUpInside)

let addButtonImage = UIImage(named: "AddFriend")

self.friendButton.setImage(addButtonImage, forState: .Normal)
self.friendButton.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
self.friendButton.imageView?.image = addButtonImage
// Not working here
self.friendButton.imageView?.tintColor = UIColor.whiteColor()
return self.friendButton


As it says in the documentation:

- imageWithRenderingMode:

Creates and returns a new image object with the specified rendering mode.

So just writing addButtonImage?.imageWithRenderingMode(.AlwaysTemplate) doesn't change the addButtonImage. The way to use it would be like this:

var addButtonImage = UIImage(named: "AddFriend")
addButtonImage = addButtonImage?.imageWithRenderingMode(.AlwaysTemplate)

or you can simply use this one line:

let addButtonImage = UIImage(named: "AddFriend")?.imageWithRenderingMode(.AlwaysTemplate)