圖文混排實現方式
- 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;