Search code examples
iosobjective-cobjective-c-category

Category that returns array of uicolors


I have the following category extension of UIColor:

.h

#import <UIKit/UIKit.h>

@interface UIColor (Colors)
- (NSArray *)reds;
@end

.m

#import "UIColor+Colors.h"

@implementation UIColor (Colors)

- (NSArray *)reds {
    return [[NSArray alloc] initWithObjects:[UIColor colorWithRed:1.0/255.0 green:50.0/255.0 blue:98.0/255.0 alpha:1],[UIColor colorWithRed:1.0/255.0f green:37.0f/255.0f blue:75.0f/255.0f alpha:1],[UIColor colorWithRed:1.0/255.0 green:1.0/255.0 blue:52.0/255.0 alpha:1],[UIColor colorWithRed:90.0/255.0 green:13.0/255.0 blue:1.0/255.0 alpha:1],[UIColor colorWithRed:53.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1], nil];
}

@end

Then in a viewcontroller, I'm trying to do something like this: [cell setBackgroundColor:[UIColor reds][0]]; Any idea what I'm doing wrong?


Solution

  • I think the most likely problem is that the function reds needs to be a class method for you to be able to call reds on the class. So something like this:

    .h

    @interface UIColor (Colors)
       +(NSArray *)reds;
    @end
    

    .m

    @implementation UIColor (Colors)
    
    +(NSArray *)reds {
        return @[[UIColor colorWithRed:1.0/255.0 green:50.0/255.0 blue:98.0/255.0 alpha:1],
                 [UIColor colorWithRed:1.0/255.0f green:37.0f/255.0f blue:75.0f/255.0f alpha:1],
                 [UIColor colorWithRed:1.0/255.0 green:1.0/255.0 blue:52.0/255.0 alpha:1],
                 [UIColor colorWithRed:90.0/255.0 green:13.0/255.0 blue:1.0/255.0 alpha:1],
                 [UIColor colorWithRed:53.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1]];
    }
    
    @end
    

    So basically a + instead of a -. If you use - it is an instance method so you'd have to instantiate an instance of UIColor to call reds.