#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
/**
* 基类富文本
*/
@interface WJAttributeStyle : NSObject
@property (nonatomic,strong)NSString *attributeName;
@property (nonatomic,strong)id value;
@property (nonatomic,assign)NSRange range;
+ (WJAttributeStyle *)attributeName:(NSString *)attributeName value:(id)value range:(NSRange)range;
@end
#import "WJAttributeStyle.h"
@implementation WJAttributeStyle
+ (WJAttributeStyle *)attributeName:(NSString *)attributeName value:(id)value range:(NSRange)range {
WJAttributeStyle *style = [[self class] new];
style.attributeName = attributeName;
style.value = value;
style.range = range;
return style;
}
@end
#import "WJAttributeStyle.h"
#import "WJForeGroundColorStyle.h"
/**
* 颜色富文本
*/
@interface WJForeGroundColorStyle : WJAttributeStyle
+ (WJForeGroundColorStyle *)withColor:(UIColor *)color range:(NSRange)range;
@end
#import "WJForeGroundColorStyle.h"
@implementation WJForeGroundColorStyle
+ (WJForeGroundColorStyle *)withColor:(UIColor *)color range:(NSRange)range {
WJForeGroundColorStyle *style =
(WJForeGroundColorStyle *)[WJForeGroundColorStyle attributeName:NSForegroundColorAttributeName value:color range:range];
return style;
}
@end
#import "WJAttributeStyle.h"
/**
* 大小富文本
*/
@interface WJFontStyle : WJAttributeStyle
+ (WJFontStyle *)withFonte:(UIFont *)font range:(NSRange)range;
@end
#import "WJFontStyle.h"
@implementation WJFontStyle
+ (WJFontStyle *)withFonte:(UIFont *)font range:(NSRange)range {
WJFontStyle *style =
(WJFontStyle *)[WJFontStyle attributeName:NSFontAttributeName value:font range:range];
return style;
}
@end
#import <Foundation/Foundation.h>
#import "WJAttributeStyle.h"
#import "WJForeGroundColorStyle.h"
#import "WJFontStyle.h"
@interface NSString (WJAttributeStyle)
/**
* 根据styles数组创建出富文本
*
* @param styles WJAttributeStyle对象构成的数组
*
* @return 富文本
*/
- (NSAttributedString *)createAttributeStringWithStyles:(NSArray *)styles;
@end
#import "NSString+WJAttributeStyle.h"
@implementation NSString (WJAttributeStyle)
- (NSAttributedString *)createAttributeStringWithStyles:(NSArray *)styles {
if (self.length <= 0) {
return nil;
}
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:self];
for (int i = 0; i < styles.count; i ++) {
WJAttributeStyle *style = styles[i];
[attributeString addAttribute:style.attributeName
value:style.value
range:style.range];
}
return attributeString;
}
@end
NSString *string = @"这是一个测试";
_label.attributedText = [string createAttributeStringWithStyles:
@[[WJAttributeStyle attributeName:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(0, 1)],
[WJForeGroundColorStyle withColor:[UIColor grayColor] range:NSMakeRange(1, 1)],
[WJFontStyle withFonte:[UIFont systemFontOfSize:30] range:NSMakeRange(2, 1)]
]];