#import <UIKit/UIKit.h>
@interface UILabel (Attribute)
@property (nonatomic, copy) NSString *newText;
@property (nonatomic, strong) UIFont *newFont;
@end
#import "UILabel+Attribute.h"
#import "objc/Runtime.h"
@implementation UILabel (Attribute)
static NSString * newFontKey = @"newFontKey";
static NSString * newTextKey = @"newTextKey";
#pragma mark - 使用runtime增加newFont属性
-(UIFont *)newFont{
return objc_getAssociatedObject(self, &newFontKey);
}
- (void)setNewFont:(UIFont *)newFont{
objc_setAssociatedObject(self, &newFontKey, newFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.font = [newFont fontWithSize:newFont.pointSize/2];
}
#pragma mark - 使用runtime增加newFont属性
- (NSString *)newText{
// 利用runtime添加属性
return objc_getAssociatedObject(self, &newTextKey);
}
-(void)setNewText:(NSString *)newText{
// 利用runtime添加属性
objc_setAssociatedObject(self, &newTextKey, newText, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
NSMutableString *str = [[NSMutableString alloc] initWithString:newText];
NSInteger count = str.length;
for (int i = 1; i < count; i ++) {
[str insertString:@"\n" atIndex:i*2-1];
}
self.text = str;
self.numberOfLines = 0;
}
@end
调用
UILabel *showTitleLabel=[[UILabel alloc]initWithFrame:CGRectMake(20, 200, 50, 100)]; //在图片上面添加UILabel
showTitleLabel.textColor=[UIColor whiteColor];
showTitleLabel.textAlignment=NSTextAlignmentCenter;
showTitleLabel.backgroundColor = [UIColor orangeColor];
showTitleLabel.newFont=[UIFont systemFontOfSize:28];
showTitleLabel.newText = @"给Label增加属性";
[self.view addSubview:showTitleLabel];