简体   繁体   中英

tintColor of UIButton's ImageView is not changing

How to change tintColor of button.imageView . If I use the same image in UIImageView with the same rendering mode as below the tintColor will change but the same is not happening for button's image view. Is it because of buttonType ?

    UIButton *frontButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [frontButton setImage:[[UIImage imageNamed:FRONT_IMAGE] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [frontButton.imageView setTintColor:[UIColor redColor]];
    [self addSubview:frontButton];

Set Button type "System" and then set tint color. This solution will definitely work. Please try this

UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
 [btn setTintColor:YOUR_COLOR];
 [btn setImage:YOUR_Image];

Try This code to change the tint color inside Button :

UIButton *frontButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:FRONT_IMAGE]];
imageV.image = [imageV.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageV.tintColor = [UIColor redColor];
[frontButton setImage:imageV.image forState:UIControlStateNormal];

you can do something like,

UIButton *frontButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[frontButton setImage:[[UIImage imageNamed:FRONT_IMAGE] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
[frontButton setTintColor:[UIColor redColor]];
[self addSubview:frontButton];

Set tint color to button and if image rendering mode is template then it will also get this tint color.

If you want different tint color for button and different for image then you should take one temporary imageview and set image to that imageview with rendering mode template and then set tint color to that imageview and then set image to button from that imageview.

Hope this will help :)

Swift 4.0

extension UIImage {
    public static func imageWithRenderingModeAlwaysTemplate(named: String) -> UIImage? {
        let image = UIImage(named: named)?.withRenderingMode(.alwaysTemplate)
        let imageView = UIImageView(image: image)
        return imageView.image
    }
}

Using

let button = UIButton.setImage(UIImage.imageWithRenderingModeAlwaysTemplate(named: ""), for: .normal)
button.tintColor = .red

我找到了答案,在设置了问题中提到的渲染模式后,我只需要将tintColor赋予UIButton而不是按钮的imageView属性。

[button setTintColor:YOUR_COLOR];

Xamarin iOs Solution:

  var image = uiButton.ImageView.Image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
  uiButton.SetImage(image, UIControlState.Normal);
  uiButton.TintColor = effect.TintColor.ToUIColor();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM