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

链式编程在实现对象的拼接上有奇效,能用最简洁的代码实现最全的功能,其中最广为人知的应该就是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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,204评论 4 61
  • 第四次作业用时2小时
    珍妮宝贝_3d80阅读 2,383评论 0 0
  • 1 很多年以后的一个晚上,闺蜜给我留言写道:“他越优秀我越害怕”,是找到对象了吗?我心中疑惑,回复道:“他是谁?”...
    正好周沫阅读 2,299评论 0 1
  • 1华鑫报告2评级3生产4二维码流程分析需那些条件如何解决5谈要求6梳理保险流程查找缺少条件如何解决7开拓客户流程缺...
    010ed0d5a362阅读 1,293评论 0 0
  • 你的内心渴望什么,你的脑子就会装满什么,你的眼睛就会看到什么,你的世界就会充满什么,你的人生就会追逐什么,你的最后...
    前端宝宝阅读 2,924评论 0 0