不能继承UIColor? [英] Can't subclass UIColor?
本文介绍了不能继承UIColor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将UIColor子类化,我似乎无法弄清楚出了什么问题。
I'm trying to subclass UIColor, and I can't seem to figure out what's wrong.
在我的PColor.h中
In my PColor.h
#import <Foundation/Foundation.h>
@interface PColor : UIColor {
BOOL isAvailable;
int colorId;
}
@property (nonatomic, assign) BOOL isAvailable;
@property (nonatomic, assign) int colorId;
@end
...和我的PColor.m
...and in my PColor.m
#import "PColor.h"
@implementation PColor
@synthesize isAvailable;
@synthesize colorId;
@end
在实例化PColor对象时,我得到:
Upon instantiating a PColor object, I get:
//warning: incompatible Objective-C types initializing 'struct UIColor *', expected 'struct PColor *'
PColor *pcolor = [[PColor alloc] initWithHue:1 saturation:0 brightness:0 alpha:1];
我错过了什么吗?在此先感谢。
Am I missing something? Thanks in advance.
推荐答案
UIColor
是一个类集群使用关联参考在一个类别中添加属性! UIColor
上的所有自定义init方法都返回 UIColor *
而不是 id
所以你不能轻易地继承 UIColor
,也不应该尝试。
UIColor
is a class cluster use associative references in a category to add properties! All of the custom init methods on UIColor
return a UIColor*
not an id
so you can not easily subclass UIColor
nor should you try.
UIColor + PCOLOR.h
UIColor+PCOLOR.h
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@interface UIColor(PCOLOR)
//Properties prefixed to try and avoid future conflicts
@property (nonatomic, assign) BOOL pIsAvailable;
@property (nonatomic, assign) int pColorId;
@end
UIColor + PCOLOR.h
UIColor+PCOLOR.h
#import "UIColor+PCOLOR.h"
@implementation UIColor(PCOLOR)
static char PCOLOR_ISAVAILABLE_KEY;
static char PCOLOR_COLORID_KEY;
@dynamic pIsAvailable, pColorId;
-(void)setPIsAvailable:(BOOL)pIsAvailable
{
objc_setAssociatedObject(self, &PCOLOR_ISAVAILABLE_KEY, [NSNumber numberWithBool:pIsAvailable], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(BOOL)pIsAvailable
{
return [(NSNumber*)objc_getAssociatedObject(self, &PCOLOR_ISAVAILABLE_KEY) boolValue];
}
-(void)setPColorId:(int)pColorId
{
objc_setAssociatedObject(self, &PCOLOR_COLORID_KEY, [NSNumber numberWithInt:pColorId], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(int)pColorId
{
return [(NSNumber*)objc_getAssociatedObject(self, &PCOLOR_COLORID_KEY) intValue];
}
@end
USAGE
UIColor *pcolor = [[UIColor alloc] initWithHue:1 saturation:0 brightness:0 alpha:1];
pcolor.pColorId = 2352;
pcolor.pIsAvailable = YES;
NSLog(@"\nClass: %@\nColor ID: %d\nIs Availabled: %@",
NSStringFromClass([pcolor class]),
pcolor.pColorId,
pcolor.pIsAvailable ? @"YES" : @"NO");
[pcolor release];
这篇关于不能继承UIColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文