ios - 如何在自定义类型的 UIButton 中设置 ImageView 的颜色?

标签 ios swift uibutton

我已经尝试了所有方法,但没有任何反应。它只是保持黑色。我错过了什么吗?我尝试使用 UIButton 的 ImageView ,但它没有做出任何改变。

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(_:)

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

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

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

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

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

关于ios - 如何在自定义类型的 UIButton 中设置 ImageView 的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39431695/

相关文章:

iphone - NSDictionary 没有正确存储 CGRect?

swift - 如何统一填充 SKShapeNode

ios - 在 Swift 中使用 RestKit

ios - TouchDown 上的自定义 UIButton

ios - 是否可以自定义区域形状?核心位置

ios - 在没有 Childbrowser 插件的 iOS 中使用 Phonegap Cordova 打开外部链接

ios - Objective-C 中的混合或多重继承?

ios - 使用 NBAsYouTypeFormatter 实时格式化电话号码

cocoa-touch - UIButton 触摸和按住

ios - 在iOS模拟器中检测UIButton上的长按