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

时间:2017-01-09 10:14:52

标签: ios objective-c uibutton tintcolor uiedgeinsets

我在Objective-c应用程序中有一个UIButton。我的按钮被修改为添加文字和图像,如:

- (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];

我有这个: enter image description here

我想得到它: enter image description here

我怎样才能改变imageButton的颜色?

6 个答案:

答案 0 :(得分:2)

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

1.拖动Assets.xcassets上的图片并在资产属性检查器中将渲染为属性更改为Template Image

enter image description here

2.并按照以下方式设置所需的色调颜色。

icon.tintColor = [UIColor redColor];

希望它会对你有所帮助。

答案 1 :(得分:1)

在Interface Builder中将UIButtonType更改为UIButtonTypeCustom,或使用

以编程方式更改
 UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom]; 

自行更改属性并重新创建圆角

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

让我知道状态..

答案 2 :(得分:1)

创建一个图层,然后在按钮上的ImageView中设置所需的颜色和蒙版。

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

答案 3 :(得分:1)

更改tintColor属性的解决方案是setImage with renderingMode:

 imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate

使用此代码:

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

然后使用此代码将图像设置为按钮,我们可以正确设置tintColor属性:

 self.myButton.tintColor = [UIColor redColor];

答案 4 :(得分:0)

Swift 4和4.2

Array
(
    [0] => Array
        (
            [0] => blablablablablabl        
            [1] => Jo Byung Gyu
            [2] => https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT5ynS8xnQneaIWFdHzy8A11dwG57pZHwAXh2OCDVaOfLMYyE354Y9NMhsDkx7IeFAduMx8Q_uIhiburan 
            [3] => http://www.tribunnews.com/section/2019/02/21/pemeran-sky-castle-jo-byung-gyu-dan-kim-bo-ra-resmi-berpacaran-intip-momen-mereka-saat-berkencan
        )

enter image description here

答案 5 :(得分:0)

快捷键5

let examButton = UIButton(image: UIImage(systemName: "rectangle.dock")!, tintColor: .systemRed, target: self, action: #selector(showExamController))

examButton.setTitleColor(.label, for: .normal)
examButton.setTitle("   12K", for: .normal)