Wrappres' Studio.

应对富文本需求

字数统计: 275阅读时长: 1 min
2020/02/16 Share

应对富文本需求

富文本是一段有属性的字符串,可以包含不同字体,不同字号,不同背景,不同颜色,不同字间距的文字,还可以设置段落,图文混排等等属性。

WebView

1
2
3
4
5
6
7
8
9
10
11
12
13
self.wbView = [[UIWebView alloc] init];
self.wbView.delegate = self;
[self.view addSubview:self.wbView];
[self.wbView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.bottom.equalTo(self.view);
}];
self.wbView.scalesPageToFit = YES; // 确保网页的显示尺寸和屏幕大小相同
self.wbView.scrollView.directionalLockEnabled = YES; // 只在一个方向滚动
self.wbView.scrollView.showsHorizontalScrollIndicator = NO; // 不显示左右滑动
[self.wbView setOpaque:NO]; // 默认是透明的

// 读取文章 html 字符串进行展示
[self.wbView loadHTMLString:articleString baseURL:nil];

在Cocoa层使用NSURLProtocol可以拦截所有HTTP的请求,可以以此来缓存文章中的图片。

YYText

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
NSMutableAttributedString *text = [NSMutableAttributedString new];
UIFont *font = [UIFont systemFontOfSize:16];
NSMutableAttributedString *attachment = nil;

// 嵌入 UIImage
UIImage *image = [UIImage imageNamed:@"dribbble64_imageio"];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];

// 嵌入 UIView
UISwitch *switcher = [UISwitch new];
[switcher sizeToFit];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:switcher contentMode:UIViewContentModeBottom attachmentSize:switcher.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];

// 嵌入 CALayer
CASharpLayer *layer = [CASharpLayer layer];
layer.path = ...
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:layer contentMode:UIViewContentModeBottom attachmentSize:switcher.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];
CATALOG
  1. 1. 应对富文本需求
    1. 1.1. WebView
    2. 1.2. YYText