A-A+

从Masonry的链式写法到iOS的富文本封装

2020年08月08日 iOS入门教程 暂无评论
博客主机

作为iOS应用开发者一定对Masonry非常了解,它的链式写法使得布局工作得心应手,高内聚的代码块也使得代码更加整洁清爽,相比于Auto Layout大大提高了开发效率。那么我们又如何汲取这种链式编程的思想,从而封装出简单好用的工具类呢?本期笔者通过对iOS中的常用富文本的一些封装,来做些简单的阐述,期望能够抛砖引玉。 话不多说先上demo:YsyRichText

痛点:我们在使用NSMutableAttributedString的时候,动辄需要写各种段落样式,添加各种AttributeName,value,range,诸如

[attributedString addAttribute:NSFontAttributeName
                                 value:value
                                 range:NSMakeRange(0, string.length)];

我们不仅要记住各种AttributeName,还要计算range,除此之外我们每添加一种样式,又得重复一次这样的过程,使得大段大段的代码极其繁琐。

1-2

所以笔者想到能不能像Masonry一样,链式调用,代码内聚,清爽干净。我想到的第一步是给NSString添加一个分类方法,像这样。用字符串调用,返回值是富文本,通过中间件make链式添加样式。这个中间件make封装了NSMutableAttributedString的一些常用基本样式。

///设置font
- (AttributedMaker *(^)(UIFont *value))font;
///设置斜体
- (AttributedMaker *(^)(float value))obliqueness;
///设置文字颜色
- (AttributedMaker *(^)(UIColor *value))foregroundColor;
///设置背景颜色
- (AttributedMaker *(^)(UIColor *value))backgroundColor;
///删除线高度
- (AttributedMaker *(^)(NSInteger value))strikethroughStyle;
///删除线颜色
- (AttributedMaker *(^)(UIColor *value))strikethroughColor;
///下滑线粗度
- (AttributedMaker *(^)(NSInteger value))underlineStyle;
///下滑线颜色
- (AttributedMaker *(^)(UIColor *value))underlineColor;
///字体描边宽度
- (AttributedMaker *(^)(float value))strokeWidth;
///字体描边颜
- (AttributedMaker *(^)(UIColor *value))strokeColor;
///字体阴影
- (AttributedMaker *(^)(NSShadow *value))shadow;
///字间距
- (AttributedMaker *(^)(float value))kern;
///行间距
- (AttributedMaker *(^)(float value))lineSpacing;
///对齐方式
- (AttributedMaker *(^)(NSTextAlignment value))textAlignment;
///字符截断类型
- (AttributedMaker *(^)(NSLineBreakMode value))lineBreakMode;
///设置URL跳转 UITextView才有效,UILabel和UITextField里面无效
- (AttributedMaker *(^)(NSString *value))link;
///插入图片(图片,尺寸,位置)
- (AttributedMaker *(^)(UIImage *image,CGRect bounds,NSInteger index))insertImage;
///追加文字
- (AttributedMaker *(^)(NSString *string))append;
///合并(例如追加完文字以后,来个总设置)
- (AttributedMaker *)merge;

最后使用方法最终效果如下

      UITextView *textView = [UITextView new];
        

[self.view addSubview:textView]

; textView.frame = CGRectMake(100, 100, 200, 100); textView.backgroundColor = [UIColor orangeColor]; textView.attributedText = [@"富文本:" ysy_Attributed:^(AttributedMaker *make) { make.font([UIFont systemFontOfSize:12]).foregroundColor([UIColor blueColor]).obliqueness(0.5); make.append(@"追加文字追加文字追加文字追加文字").font([UIFont systemFontOfSize:17]).foregroundColor([UIColor redColor]); make.merge.backgroundColor([UIColor yellowColor]); make.strikethroughStyle(1).strikethroughColor([UIColor whiteColor]).lineSpacing(15).textAlignment(NSTextAlignmentLeft); make.underlineStyle(2).underlineColor([UIColor blueColor]); make.insertImage([UIImage imageNamed:@"10.jpg"],CGRectMake(0, -5, 20, 20),10); }];复制代码

标签:

给我留言

Copyright © ios教程,苹果粉丝,苹果资讯,ios入门教程,ios学习,ios程序员,ios视频教程,ios粉丝网 保留所有权利.   Theme  Ality

用户登录