添加自定义类别 - Obj C.

时间:2014-02-21 03:24:56

标签: ios objective-c-category

我在添加自定义uicolor

时遇到问题

我有一个.h和一个.m文件,都名为custcolors

以下是我的custColors.h文件:

#import <UIKit/UIKit.h>

@interface UIColor (MyCatagory)
+ (UIColor*) customRedColor;
@end

以下是我的custColors.m文件:

#import "custColors.h"

@implementation UIColor (MyCategory)

+ (UIColor *)customRedColor {
    return [UIColor colorWithHexString:@"88C800"];
}
-(UIColor*)colorWithHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

    if ([cString length] != 6) return  [UIColor grayColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

@end

我的问题是,当我尝试使用它时,我只是得到一个错误。说;

custColors.h:12:33: Expected identifier
custColors.h:12:35: Expected an Objective-C directive after '@'
custColors.m
custColors.m:13:51: Use of undeclared identifier 'hex'

我要做的是创建一个自定义的十六进制颜色,我可以使用它来实现每个视图控制器,以将其背景颜色更改为此。

建议,想法?

1 个答案:

答案 0 :(得分:1)

似乎colorWithHexString应该是类方法,而不是实例方法。 将其更改为:

+ (UIColor*)colorWithHexString:(NSString*)hex {

    ...
}