在分類中添加屬性驴一,使用對象關(guān)聯(lián)來實現(xiàn):
例子:創(chuàng)建一個label的分類
#import
@interfaceUILabel (FontAndColor)
@property (nonatomic, copy) NSString *name;//分類中創(chuàng)建了一個name屬性
-(void)WithFont:(int)font withColor:(UIColor*)color withTextAlig:(NSTextAlignment)texAli;
@end
#import "UILabel+FontAndColor.h"
#import
@implementationUILabel (FontAndColor)
static NSString *key = @"associatedObject";
-(void)WithFont:(int)font withColor:(UIColor*)color withTextAlig:(NSTextAlignment)texAli{
? ? self.font = [UIFont systemFontOfSize:font];
? ? self.textColor= color;
? ? self.textAlignment= texAli;
}
-(void)setName:(NSString*)name{//關(guān)聯(lián)實現(xiàn)
? ? objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString*)name{//獲取值
? ? return objc_getAssociatedObject(self, _cmd);
}
@end