【问题标题】:How to set the color of the image view in UIButton on type Custom?如何在自定义类型的 UIButton 中设置图像视图的颜色?
【发布时间】:2017-01-18 19:00:52
【问题描述】:

我已经尝试了所有方法,但没有任何反应。它只是保持黑色。我错过了什么吗?我尝试使用 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
}()

【问题讨论】:

  • AddFriend图片的文件格式是什么?
  • 这是一个 png 文件。当我尝试系统时,它可以工作,但我需要使用自定义来满足我的要求。
  • 尝试在 XCAssets 中设置渲染模式,而不是在代码中。检查这个线程。 stackoverflow.com/a/27122597/4475605
  • 好的,我设置好了,可惜按钮还是不是白色的。
  • “设置图像颜色”是什么意思?图像由具有固定颜色的像素组成。您无法更改按钮中安装的图像的颜色。

标签: ios swift uibutton


【解决方案1】:

正如documentation 中所说:

- withRenderingMode(_:)

创建并返回具有指定渲染模式的新图像对象。

所以只写addButtonImage?.withRenderingMode(.alwaysTemplate) 不会改变addButtonImage。使用方法是这样的:

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

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

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

【讨论】:

  • 好的,明白了!我认为这就是我出错的地方。
【解决方案2】:

Sam_M 的答案已更新到 Swift 3:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2012-08-03
    • 2017-03-04
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多