Colors in Objective-C

With this post I start annotating some basic tips on Apple programming, as most newbies do.

We want to change the text and color of a label:

MyName.text = [[listNames objectAtIndex:i] uppercaseString] ;
[MyName setTextColor:[UIColor colorWithRed:22.0/255.0f green:150.0/255.0f blue:22.0/255.0f alpha:1.0]] ;

Thanks to Stack Overflow I stumbled upon a macro:

#define RGB(r, g, b) [UIColor colorWithRed:(float)r / 255.0 green:(float)g / 255.0 blue:(float)b / 255.0 alpha:1.0]
#define RGBA(r, g, b, a) [UIColor colorWithRed:(float)r / 255.0 green:(float)g / 255.0 blue:(float)b / 255.0 alpha:a]

To be used like:

[attributedString addAttribute:NSForegroundColorAttributeName
                         value:RGB(66, 79, 91)
                         range:NSMakeRange(0, attributedString.length)];

Using like:

[attributedString addAttribute:NSForegroundColorAttributeName
                         value:RGB(66, 79, 91)
                         range:NSMakeRange(0, attributedString.length)];

Again via Stack Overflow (what else?) there’s a good tip to define a color to be used globally:

File .h

#import <UIKit/UIKit.h>

@interface UIColor (CustomColors)
+ (UIColor *)myColorLightGreyBGColor;
@end

File .m

#import "UIColor+CustomColors.h"

@implementation UIColor (CustomColors)

+ (UIColor *)myColorLightGreyBGColor {
    static UIColor *lightGreyBGColor;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lightGreyBGColor = [UIColor colorWithRed:241.0 / 255.0
                                           green:241.0 / 255.0
                                            blue:241.0 / 255.0
                                           alpha:1.0];
    });
    return lightGreyBGColor;
}
@end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s