Author Topic: How can I create a UIColor that can be accessed anywhere in my project?  (Read 3341 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
Often, apps use a custom background color throughout the app to help brand the app. If you want to declare a custom color that can be accessed from anywhere within your app, you can create an Objective-C category that extends the UIColor class (see Book 2: Flying With Objective-C, Chapter 16: Advanced Objective-C under the section Extending Classes with Categories for more info):


1. Create a new category based on UIColor. For example, here is the .h file:
Code: [Select]
#import <UIKit/UIKit.h>

@interface UIColor (BurgundyColor)

+ (UIColor*)burgundyColor;

@end

And here is the .m file:

Code: [Select]
#import "UIColor+BurgundyColor.h"

@implementation UIColor (BurgundyColor)

+ (UIColor*)burgundyColor {
   
    return [UIColor colorWithRed:180.0/255.0 green:20.0/255.0 blue:30.0/255.0 alpha:1];
}

@end

2. Add a reference to the new category in your project's .pch file (located under the Supporting Files group). For example:

Code: [Select]
#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
    #import "UIColor+BurgundyColor.h"
#endif

3. Now you can reference the new color from anywhere in your project. For example:
Code: [Select]
[[UINavigationBar appearance] setBarTintColor:[UIColor burgundyColor]];
All the best!
Kevin McNeish
Author of "Learn to Code in Swift": https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11
« Last Edit: July 18, 2015, 03:22:31 PM by kjmcneish »