Using a UIColor category in iOS 7 and Objective c

2019-08-03 12:20发布

问题:

I have a UIColor+MyLayout.m file such as:

@implementation UIColor (Layout)

- (UIColor *) textBackground
{
    UIColor *lightGreen = [UIColor colorWithRed:0.0f/255.0f green:178.0f/255.0f     blue:238.0f/255.0f alpha:1.0f];

    return lightGreen;
}

@end

I have added the .h file to my viewcontroller.m, but how do I call this into a UIColor?

UIColor *myColor = ?

回答1:

Would be better if you do the following:

@implementation UIColor (Layout)

+ (UIColor *) textBackground {
    UIColor *lightGreen = [UIColor colorWithRed:0.0f/255.0f green:178.0f/255.0f        blue:238.0f/255.0f alpha:1.0f];
    return lightGreen;
}

@end

And then just call it UIColor *myColor = [UIColor textBackground];



回答2:

Huge screenshot showing coloured text

TRY THIS.... IT IS WORKING!!!!

1. MAke the subclass of UIColor named vv.

So, in UIColor+vv.h

#import <UIKit/UIKit.h>

@interface UIColor (vv)
+(UIColor*)mh;
@end

UIColor+vv.m

#import "UIColor+vv.h"

@implementation UIColor (vv)
+(UIColor*)mh
{
     UIColor *lightGreen = [UIColor colorWithRed:0.0f/255.0f green:178.0f/255.0f     blue:238.0f/255.0f alpha:1.0f];
    return lightGreen;
}
@end

ViewController.m

#import "UIColor+vv.h"

- (void)viewDidLoad
{
    lbl.textColor=[UIColor mh];
}

LET me know if you have any problem.



回答3:

You should make this method static like...

@implementation UIColor (Layout)

+ (UIColor *) textBackground {
    UIColor *lightGreen = [UIColor colorWithRed:0.0f/255.0f green:178.0f/255.0f        blue:238.0f/255.0f alpha:1.0f];
    return lightGreen;
}

@end

And then just call it using class name like

UIColor *myColor = [UIColor textBackground];

You should import UIColor+MyLayout.h like

#import UIColor+MyLayout.h



回答4:

First you have to import your category file in your class like:

#import "UIColor+Layout.h"

Then you need to call this method as

[UIColor textBackground]

Also you need to make your category method as a class method



回答5:

You can turn textBackground into class method by using + in signature instead of - and then simply:

UIColor *myColor = [UIColor textBackground];