I noticed that when I place a white or black UIImage into a UISegmentedControl it automatically color masks it to match the tint of the segmented control. I thought this was really cool, and was wondering if I could do this elsewhere as well. For example, I have a bunch of buttons that have a uniform shape but varied colors. Instead of making a PNG for each button, could I somehow use this color masking to use the same image for all of them but then set a tint color or something to change their actual color?


当前回答

如果你有一个带有背景图像的自定义按钮。您可以设置您的按钮的色调颜色和覆盖以下图像。

在资产中选择你想设置色调的按钮背景。

在图像的属性检查器中设置渲染值为“Template image”

现在当你setbutton时。tintColor = UIColor。红色“您”按钮将以红色显示。

其他回答

Swift 4与customType:

let button = UIButton(frame: aRectHere)
    let buttonImage = UIImage(named: "imageName")
    button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
    button.tintColor = .white

以上都不适合我,因为点击后色调被清除。我必须使用

button.setImageTintColor(Palette.darkGray(), for: UIControlState())

在Swift中,你可以这样做:

var exampleImage = UIImage(named: "ExampleImage.png")?.imageWithRenderingMode(.AlwaysTemplate)

然后在viewDidLoad中

exampleButtonOutlet.setImage(exampleImage, forState: UIControlState.Normal)

并修改颜色

exampleButtonOutlet.tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) //your color

编辑Xcode 8 现在你也可以在你的.xcassets to Template image中设置图像的呈现模式,然后你就不需要在var exampleImage中特别声明它了

let button = UIButton(type: .custom)
let image = UIImage(named: "image_name")?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = UIColor.red

如果你在设置UIButton。tintColor by UIColor(r:g:b:alpha:),记住值除以255。这些RGB值应该在0和1之间。

Xamarin的。iOS (c#):

UIButton messagesButton = new UIButton(UIButtonType.Custom);
UIImage icon = UIImage.FromBundle("Images/icon.png");
messagesButton.SetImage(icon.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal);
messagesButton.TintColor = UIColor.White;
messagesButton.Frame = new RectangleF(0, 0, 25, 25);