Modify UIImage renderingMode from a storyboard/xib file

前端 未结 16 2381
别那么骄傲
别那么骄傲 2020-12-02 08:00

Is it possible to modify a UIImage\'s renderingMode from a storyboard or xib editor?

The goal is to apply tintColor to the par

16条回答
  •  广开言路
    2020-12-02 08:29

    Using the template rendering mode with a UIImageView in a storyboard or xib is very buggy, both on iOS 7 and iOS 8.

    On iOS 7

    The UIImage is not properly decoded from the storyboard/xib. If you inspect the imageView.image.renderingMode property in the viewDidLoad method, you will notice that it is always UIImageRenderingModeAutomatic, even if you set it to Render As Template Image in your xcassets file.

    To workaround, you have to manually set the rendering mode:

    self.imageView.image = [self.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    

    On iOS 8

    The UIImage is properly decoded and its renderingMode property reflects what was chosen in the xcassets file but the image is not tinted.

    To workaround, you have two options:

    1. Set the tintColor property in the User Defined Runtime Attributes instead of the Attributes inspector pane.

    or

    1. Manually reset the tintColor:
    UIColor *tintColor = self.imageView.tintColor;
    self.imageView.tintColor = nil;
    self.imageView.tintColor = tintColor;
    

    You can pick your preferred option, both properly tint the image.

    (If you are compiling with Xcode 6.2, just doing self.imageView.tintColor = self.imageView.tintColor; is enough but this doesn’t work anymore if you are compiling with Xcode 6.3)

    Conclusion

    If you need to support both iOS 7 and iOS 8, you’ll need both workarounds. If you only have to support iOS 8, only one workaround is needed.

提交回复
热议问题