如何在自定义类型的 UIButton 中设置图像视图的颜色? [英] How to set the color of the image view in UIButton on type Custom?

查看:37
本文介绍了如何在自定义类型的 UIButton 中设置图像视图的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了一切,但什么也没发生.它只是保持黑色.我错过了什么吗?我尝试使用 UIButton 的图像视图,但没有改变.

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")
    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
}()

推荐答案

正如 文档:

- withRenderingMode(_:)

- withRenderingMode(_:)

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

所以只写addButtonImage?.withRenderingMode(.alwaysTemplate) 不会改变addButtonImage.使用方法如下:

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

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

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

or you can simply use this one line:

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

这篇关于如何在自定义类型的 UIButton 中设置图像视图的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆