如何在自定义类型的UIButton中设置图像视图的颜色?

时间:2016-09-11 00:08:09

标签: ios swift uibutton

我已经尝试过一切,没有任何事情发生。它只是保持黑色。我错过了什么吗?我尝试使用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
}()

2 个答案:

答案 0 :(得分:5)

正如documentation中所述:

  

- withRenderingMode(_:)

     

使用指定的渲染模式创建并返回一个新图像对象。

因此,只需撰写addButtonImage?.withRenderingMode(.alwaysTemplate)即可更改addButtonImage。使用它的方式是这样的:

var addButtonImage = UIImage(named: "AddFriend")
addButtonImage = addButtonImage?.withRenderingMode(.alwaysTemplate)

或者你可以简单地使用这一行:

let addButtonImage = UIImage(named: "AddFriend")?.withRenderingMode(.alwaysTemplate)

答案 1 :(得分:0)

Sam_M的答案更新为Swift 3:

let addButtonImage = UIImage(named: "AddFriend")?.withRenderingMode(.alwaysTemplate)