Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding UIImage(named: )

I was on my way to override UIImage class method init(named:). My goal is to be able to retrieve the file name of an image.

The code would look like this:

class UIImageWithFileName: UIImage {

    let fileName: String

    override init(named:String){
        super.init(named)
    fileName = named
    }
}

This code seems to be impossible for following reasons.

I created a subclass of UIImage, started typing init... and to my surprise there was no init(named:) method to override. Here is a complete list of init methods:

enter image description here

enter image description here

How does one override UIImage init(named:)

like image 457
potato Avatar asked Aug 29 '15 09:08

potato


2 Answers

Turns out that "init(named:" is explicitly not inheritable.

If you look at the UIImage definition, you'll see this:

public class UIImage : NSObject, NSSecureCoding, NSCoding {

    public /*not inherited*/ init?(named name: String) // load from main bundle

    @available(iOS 8.0, *)
    public /*not inherited*/ init?(named name: String, inBundle bundle: NSBundle?, compatibleWithTraitCollection traitCollection: UITraitCollection?)

Which means you need to resolve or open the file yourself and pass in the raw data into the super class.

like image 111
Michael Dautermann Avatar answered Oct 18 '22 19:10

Michael Dautermann


This is a way around:

class UIImageWithName: UIImage {

var fileName: String!

func ofFile(named:String) -> UIImageWithName?{
    let cgImage = UIImage(named: named)?.CGImage
    if let validName = cgImage{
        let image = UIImageWithName(CGImage: validName)
        image.fileName = named
        return image
    }
    return nil
}

}

Not sure if it is efficient or in any way disputable. Feedback please

like image 41
potato Avatar answered Oct 18 '22 20:10

potato