Monday, May 27, 2013

Make your app colourful by using colour code

We all iOS Developers know that we can use some distinct colours in component's background or tint colour.  If we use custom colour code the apps will be more lucrative. I am giving a simple example,

I create a segmented control programatically and set the background colour using the colour code.
In viewDidLoad method I set the  navigations bar's tint colour and background the view using colorWithHexString method which returns colour according to the hexadecimal form of the colour code. I hope it will be helpful to you.


- (void)viewDidLoad
{
    [super viewDidLoad];
     self.navigationController.navigationBar.hidden=NO;
  [self.navigationController.navigationBar setTintColor:[self colorWithHexString:@"843C44"]];
    [self.view setBackgroundColor:[self colorWithHexString:@"845C44"]];
    

}



-(UIColor*)colorWithHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    
    if ([cString length] < 6) return [UIColor grayColor];
    
    
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    
    if ([cString length] != 6) return  [UIColor grayColor];
    
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}


Now you can see how colourful your apps will be.

Happy Coding

Mahboob