Using a UIColor category in iOS 7 and Objective c

2019-08-03 12:22发布

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 = ?

5条回答
聊天终结者
2楼-- · 2019-08-03 12:55

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

UIColor *myColor = [UIColor textBackground];
查看更多
迷人小祖宗
3楼-- · 2019-08-03 12:58

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.

查看更多
来,给爷笑一个
4楼-- · 2019-08-03 12:59

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];

查看更多
Summer. ? 凉城
5楼-- · 2019-08-03 13:02

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

查看更多
ゆ 、 Hurt°
6楼-- · 2019-08-03 13:11

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

查看更多
登录 后发表回答