<span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 19.5px; background-color: rgb(254, 254, 242);">使用运行时库,必须要先引入 objc/runtime.h</span>
<span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 19.5px; background-color: rgb(254, 254, 242);">看一个类别和动态添加属性的例子 UILabel+Associate.h #import <UIKit/UIKit.h> @interface UILabel (Associate) - (void) setFlashColor:(UIColor *) flashColor; - (UIColor *) getFlashColor; </span>
<span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 19.5px; background-color: rgb(254, 254, 242);">@end</span><span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 19.5px; background-color: rgb(254, 254, 242);">UILabel+Associate.m</span>
<span style="font-family: Arial, Helvetica, sans-serif;">#import "UILabel+Associate.h"</span>
#import <objc/runtime.h> @implementation UILabel (Associate) static char flashColorKey; - (void) setFlashColor:(UIColor *) flashColor{ objc_setAssociatedObject(self, &flashColorKey, flashColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (UIColor *) getFlashColor{ return objc_getAssociatedObject(self, &flashColorKey); } @end
调用代码:
UILabel *lab = [[UILabel alloc] init]; [lab setFlashColor:[UIColor redColor]]; NSLog(@"%@", [lab getFlashColor]);
时间: 2024-11-05 01:51:10