×

iOS链式编程实现富文本拼接

96
hanryChen
2017.05.16 09:35* 字数 122

链式编程在实现对象的拼接上有奇效,能用最简洁的代码实现最全的功能,其中最广为人知的应该就是masonry了。合理的使用链式编程可以大大的简化代码的耦合度和复杂性并且提高可读性。
下面就是一个简单的使用链式编程实现富文本拼接的例子:
.h文件

#import <Foundation/Foundation.h>

@interface NSMutableAttributedString (Add)

- (NSMutableAttributedString *(^)(NSString *,NSDictionary <NSString *,id > *))add;

@end

FOUNDATION_EXTERN NSString *const NSImageAttributeName;  //图片,传UIImage
FOUNDATION_EXTERN NSString *const NSImageBoundsAttributeName; //图片尺寸

.m文件

#import "NSMutableAttributedString+Add.h"

@implementation NSMutableAttributedString (Add)

- (NSMutableAttributedString *(^)(NSString *, NSDictionary<NSString *,id> *))add {
    return ^NSMutableAttributedString * (NSString *string, NSDictionary <NSString *,id>*attrDic) {
        
        if ([[attrDic allKeys] containsObject:NSImageAttributeName] && [[attrDic allKeys] containsObject:NSImageBoundsAttributeName]) {
            NSTextAttachment *attach = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
            CGRect rect = CGRectFromString(attrDic[NSImageBoundsAttributeName]);
            attach.bounds = rect;
            attach.image = attrDic[NSImageAttributeName];
            
            [self appendAttributedString:[NSAttributedString attributedStringWithAttachment:attach]];
        }
        else {
            [self appendAttributedString:[[NSAttributedString alloc] initWithString:string attributes:attrDic]];
        }
        
        return self;
    };
}


@end

NSString *const NSImageAttributeName = @"NSImageAttributeName";
NSString *const NSImageBoundsAttributeName = @"NSImageBoundsAttributeName";

调用方法:

self.tapMessageLabel.attributedText =
    [NSMutableAttributedString new]
    .add(@"红色字体,字号11",@{
                        NSForegroundColorAttributeName:[UIColor redColor],
                        NSFontAttributeName :[UIFont systemFontOfSize:11],
                        })
    .add(@"蓝色字体,字号13",@{
                        NSForegroundColorAttributeName:[UIColor blueColor],
                        NSFontAttributeName :[UIFont systemFontOfSize:13],
                        })
    .add(@"黑色字体,字号15",@{
                        NSForegroundColorAttributeName:[UIColor blackColor],
                        NSFontAttributeName :[UIFont systemFontOfSize:15],
                        });

运行:

效果图.png
日记本
Web note ad 1