图文混排实现方式
- core Text
- ios 6.0 之前,纯C语言,不易用,不推荐使用
- NSAttributedString
- ios 6.0 开始,简单易用
- TextKit
- ios7 开始,功能强大,简单易用
- UIWebView
- 利用UIWebView加载HTML实现图文混排
- 但是注意:UIWebView本身有内存问题,占用内存相比较而较大不推荐,但是使用比较灵活
1、不可变的属性文字 NSAttributedString
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
attrs[NSUnderlineStyleAttributeName] = @1;
attrs[NSUnderlineColorAttributeName] = [UIColor redColor];
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attrs];
2、可变的属性文字 NSMutableAttributedString
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.placeholder];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 1)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(1, 1)];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:30] range:NSMakeRange(1, 1)];
self.attributedPlaceholder = string;
3、图文混排
-
图解:
Snip20150902_94.png
-
注意:
Snip20150902_96.png 实现:
// 富文本用法3 - 图文混排
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
// 第二段:图片
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"login_close_icon"];
attachment.bounds = CGRectMake(0, 0, 16, 16);
NSAttributedString *subtring2 = [NSAttributedString attributedStringWithAttachment:attachment];
[string appendAttributedString:subtring2];
// 第一段:placeholder
NSAttributedString *substring1 = [[NSAttributedString alloc] initWithString:self.placeholder];
[string appendAttributedString:substring1];
// 第三段:哈哈
NSAttributedString *substring3 = [[NSAttributedString alloc] initWithString:@"哈哈"];
[string appendAttributedString:substring3];
self.attributedPlaceholder = string;