Search code examples
iosios7xcode-storyboard

Modify UIImage renderingMode from a storyboard/xib file


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

The goal is to apply tintColor to the particular UIImageView object.


Solution

  • Here's how you can do it in .xib or storyboard files:

    (Obj-C) Create a category on UIImageView:

    @interface UIImageView (Utils)
    
    - (void)setImageRenderingMode:(UIImageRenderingMode)renderMode;
    
    @end
    
    @implementation UIImageView (Utils)
    
    - (void)setImageRenderingMode:(UIImageRenderingMode)renderMode
    {
        NSAssert(self.image, @"Image must be set before setting rendering mode");
        self.image = [self.image imageWithRenderingMode:renderMode];
    }
    
    @end
    

    (Swift 4) Create an extension for UIImageView:

    extension UIImageView {
        func setImageRenderingMode(_ renderMode: UIImage.RenderingMode) {
            assert(image != nil, "Image must be set before setting rendering mode")
            // AlwaysOriginal as an example
            image = image?.withRenderingMode(.alwaysOriginal)
        }
    }
    

    Then in the Identity Inspector in the xib file, add a runtime attribute:

    enter image description here