Using a UIColor category in iOS 7 and Objective c

依然范特西╮ 提交于 2019-12-11 08:29:15

问题


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


来源:https://stackoverflow.com/questions/19397024/using-a-uicolor-category-in-ios-7-and-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!