如何用imageEdgeInsets在UIButton中更改图片的tintColor?

II在我的Objective-C应用程序中有一个UIButton。 我的button被修改添加文本和图像,如:

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing { CGFloat insetAmount = spacing / 2.0; self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount); self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount); self.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount); } 

然后我添加这个代码的图像:

 [self.myButton setImage:[UIImage imageNamed:@"imageButton.png"] forState:UIControlStateNormal]; 

我想改变图像的tintColor,但是当我尝试改变这个,我的代码是不工作的:

 [self.myButton setTintColor:[UIColor redColor]]; 

我想使用这个代码,但没有工作:

 UIImage* img = [UIImage imageNamed:imageName]; icon.image = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; icon.tintColor = [UIColor redColor]; 

我有这个: 在这里输入图像说明

我想得到它: 在这里输入图像说明

我怎么能改变imageButton的颜色?

在Interface Builder中将UIButtonType更改为UIButtonTypeCustom,或者使用编程方式

  UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom]; 

更改您自己的属性并重新创build圆angular

 myButton.backgroundColor = [UIColor redColor]; myButton.layer.borderColor = [UIColor blackColor].CGColor; myButton.layer.borderWidth = 0.5f; myButton.layer.cornerRadius = 10.0f; 

让我知道状态

创build一个图层,并在你的button中设置你想要的颜色和蒙版像这样。

 for (UIView *view in myButton.subviews) { if ([view isKindOfClass:[UIImageView class]]) { CALayer *mask = [CALayer layer]; mask.backgroundColor = [UIColor redColor].CGColor; view.layer.mask = mask; } } 

改变tintColor属性的解决scheme是使用renderingMode的setImage:

  imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate 

有了这个代码:

 [self.myButton setImage:[[UIImage imageNamed:@"myImageButton.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal]; 

然后用这个代码将图像设置为button,我们可以正确设置tintColor属性:

  self.myButton.tintColor = [UIColor redColor]; 

我们可以通过以下方式为透明图标应用所需的颜色。

1.在Assets.xcassetsAssets.xcassets图像,并在资产属性检查器中将“渲染为”属性更改为“ Template Image

在这里输入图像说明

2.如下所示设置所需的色调颜色。

 icon.tintColor = [UIColor redColor]; 

希望它会帮助你。