swiftuikituiimage

How to write UIImage extension to add tint color to the image with signature UIImage(resource, color)


Please find my code

convenience init?(resource: ImageResource, color: UIColor) {
    let image = UIImage(resource: resource).withTintColor(color)
    self.init()
}

Please mention what I am missing


Solution

  • IMO, you can convert it to cgImage or a kind of Data, something like:

    extension UIImage {
        convenience init?(resource: ImageResource, color: UIColor) {
            let _image = UIImage(resource: resource).withTintColor(color).cgImage
            if let _image {
                self.init(cgImage: _image)
            } else {
                return nil
            }
        }
    }