Sunday, July 10, 2016

UIImage from a UIColor

Many time graphic team are very busy and they are not able to provide single color image or background for my controller. So, I do google and found  Below code help me to convert UIColor to UIImage.

In Objective-c 

+ (UIImage *)imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
UIImage *img = [YourClassName imageFromColor:[UIColor blueColor]];

In Swift 2.0

extension UIImage {
    static func fromColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}  
let img = UIImage.fromColor(.blueColor())

For alpha replace 
UIGraphicsBeginImageContext(rect.size);
With
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);



























Saturday, July 2, 2016


Using a dispatch_once create a Singleton model in Swift

The traditional Objective-C approach in Swift to create a Singleton model.

One of the toughest issues to debug is the one created by the multiple instances of a class which manages the state of a single resource. It is highly desirable if we can use some Design Pattern to control the access to that shared resource. The Singleton pattern fits the bill perfectly to solve this scenario; by wrapping a singleton class around this problem ensures that there will be only one instance of the class at any given time. A most common and clichéd example for a singleton class is the one used for logging purposes where the whole application needs only one logger instance at anytime

If you opt for the lazy instantiation paradigm, then the singleton variable will not get memory until the property or function designated to return the reference is first called. This type of instantiation is very helpful if your singleton class is resource intense.




class Global: NSObject {

    var arrayDaysName: NSMutableArray! = []

    class var sharedInstance : Global {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : Global? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = Global()
        }
        return Static.instance!

    }

}

How to use?, It simple
Global.sharedInstance.arrDaysForecast = //Do what you want