在處理富文本的時(shí)候總是被一大長(zhǎng)串代碼嚇到,這篇主要介紹一種鏈?zhǔn)教幚矸椒ǎ幚砀晃谋究梢院?jiǎn)化不少代碼。PS:我也是邊學(xué)邊用,也算個(gè)筆記吧。
我們使用NSMutableAttributedString,給他添加一個(gè)分類(lèi),加一個(gè)方法即可
.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";
調(diào)用
myLabel.attributedText = [NSMutableAttributedString new].add(@"一段文本",@{@"color":[UIColor greenColor],@"font":[UIFont systemFontOfSize:12]}).add(@"第二段文本",@{@"color":[UIColor redColor],@"font":[UIFont systemFontOfSize:13]});
1.為了使方法可以使用.調(diào)用,就能不傳參,這里巧妙的使用了返回block的形式,block本身有返回值并且傳參,調(diào)用處相當(dāng)于執(zhí)行block,相當(dāng)巧妙的處理方式。
參考鏈接?http://www.itdecent.cn/p/299207775531