我已经尝试了一切,但没有任何反应。它只是保持黑色。我想念什么吗?我尝试使用UIButton的图像视图,但没有做任何更改。
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")
addButtonImage?.imageWithRenderingMode(.AlwaysTemplate)
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
}()
最佳答案
就像documentation中所说的:
-withRenderingMode(_ :)
创建并返回具有指定渲染模式的新图像对象。
因此,仅编写addButtonImage?.withRenderingMode(.alwaysTemplate)
不会更改addButtonImage
。使用方式如下:
var addButtonImage = UIImage(named: "AddFriend")
addButtonImage = addButtonImage?.withRenderingMode(.alwaysTemplate)
或者您可以只使用以下一行:
let addButtonImage = UIImage(named: "AddFriend")?.withRenderingMode(.alwaysTemplate)