在处理富文本的时候总是被一大长串代码吓到,这篇主要介绍一种链式处理方法,处理富文本可以简化不少代码。PS:我也是边学边用,也算个笔记吧。
我们使用NSMutableAttributedString,给他添加一个分类,加一个方法即可
.h文件
#import <Foundation/Foundation.h>
@interface NSMutableAttributedString (HDAttribute)
- (NSMutableAttributedString *(^)(NSString *,NSDictionary<NSString *,id>*))add;
@end
FOUNDATION_EXTERN NSString *const NSImageAttributeName;
FOUNDATION_EXTERN NSString *const NSImageBoundsAttributeName;
.m文件
#import "NSMutableAttributedString+HDAttribute.h"
@implementation NSMutableAttributedString (HDAttribute)
- (NSMutableAttributedString *(^)(NSString *,NSDictionary<NSString *,id>*))add
{
return ^NSMutableAttributedString *(NSString *string,NSDictionary<NSString *,id>*attrDic)
{
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:attrDic];
for (id key in [attributes allKeys])
{
if ([key isKindOfClass:[NSString class]])
{
if ([key isEqualToString:@"color"])
{
[attributesremoveObjectForKey:key];
[attributessetValue:[attrDic valueForKey:key] forKey:NSForegroundColorAttributeName];
}
if ([key isEqualToString:@"font"])
{
[attributesremoveObjectForKey:key];
[attributessetValue:[attrDic valueForKey:key] forKey:NSFontAttributeName];
}
}
}
if ([[attributes allKeys] containsObject:NSImageAttributeName] || [[attributes allKeys] containsObject:NSImageBoundsAttributeName])
{
NSTextAttachment *attach = [[NSTextAttachment alloc]initWithData:nil ofType:nil];
CGRect rect = CGRectFromString(attributes[NSImageBoundsAttributeName]);
attach.bounds = rect;
attach.image = attributes[NSImageAttributeName];
[self appendAttributedString:[NSAttributedString attributedStringWithAttachment:attach]];
}else
{
[self appendAttributedString:[[NSAttributedString alloc]initWithString:string attributes:attributes]];
}
return self;
};
}
@end
NSString *const NSImageAttributeName = @"NSImageAttributeName";
NSString *const NSImageBoundsAttributeName = @"NSImageBoundsAttributeName";
调用
myLabel.attributedText = [NSMutableAttributedString new].add(@"一段文本",@{@"color":[UIColor greenColor],@"font":[UIFont systemFontOfSize:12]}).add(@"第二段文本",@{@"color":[UIColor redColor],@"font":[UIFont systemFontOfSize:13]});
1.为了使方法可以使用.调用,就能不传参,这里巧妙的使用了返回block的形式,block本身有返回值并且传参,调用处相当于执行block,相当巧妙的处理方式。
参考链接 https://www.jianshu.com/p/299207775531
网友评论