加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 不能子类化UIColor?

发布时间:2020-12-16 10:18:55 所属栏目:百科 来源:网络整理
导读:我正在尝试将UIColor子类化,我似乎无法弄清楚什么是错的. 在我的PColor.h中 #import Foundation/Foundation.h@interface PColor : UIColor { BOOL isAvailable; int colorId;}@property (nonatomic,assign) BOOL isAvailable;@property (nonatomic,assign) i
我正在尝试将UIColor子类化,我似乎无法弄清楚什么是错的.

在我的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中

#import "PColor.h"

@implementation PColor
@synthesize isAvailable;
@synthesize colorId;
@end

在实例化PColor对象时,我得到:

//warning: incompatible Objective-C types initializing 'struct UIColor *',expected 'struct PColor *'
PColor *pcolor = [[PColor alloc] initWithHue:1 saturation:0 brightness:0 alpha:1];

我错过了什么吗?提前致谢.

解决方法

UIColor是一个类集群,在类别中使用 associative references来添加属性! UIColor上的所有自定义init方法都返回UIColor *而不是id,因此您不能轻易地将UIColor子类化,也不应该尝试.

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

#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

用法

UIColor *pcolor = [[UIColor alloc] initWithHue:1 saturation:0 brightness:0 alpha:1];
pcolor.pColorId = 2352;
pcolor.pIsAvailable = YES;
NSLog(@"nClass: %@nColor ID: %dnIs Availabled: %@",NSStringFromClass([pcolor class]),pcolor.pColorId,pcolor.pIsAvailable ? @"YES" : @"NO");
[pcolor release];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读