周末闲着没事,就想着不如把那些容易遗忘的知识点整理一下,一来可以让有需要的朋友少走弯路,二来自己以后再忘记的时候也可以回头看看......但 iOS 中小冷易忘的知识点实在太多了,不知道该从哪里开始整理,“百无聊赖”逛了下淘宝,发现里面好多都是富文本,就想着为什么不从富文本开始呢?反正闲着也是闲着......于是就有了下面这些东西,希望可以帮到看到的盆友们!
- 先写一个小引子
在项目中,很多时候我们都需要把文字设置成倾斜、加粗、加下划线、加删除线、加阴影等等状态,就比如下面这张图:
但如果我们只是简单的设置字体
self.textView.text = @"很好玩的富文本";
显示出来大概是这个样子滴:
为了让文字变的好看一些,接下来我们尝试一下富文本!
- 改变字体颜色
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"很好玩的富文本"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(1, 2)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, 1)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(4, 3)];
self.textView.attributedText = string;
- 改变字体大小
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"很好玩的富文本"];
[string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(1, 2)];
[string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(4, 3)];
self.textView.attributedText = string;
-
给文字添加背景色
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"很好玩的富文本"]; [string addAttribute:NSBackgroundColorAttributeName value:[UIColor cyanColor] range:NSMakeRange(1, 2)]; [string addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(4, 3)]; self.textView.attributedText = string;
-
给文字设置间距
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"很好玩的富文本"]; [string addAttribute:NSKernAttributeName value:@(20) range:NSMakeRange(0, 6)]; self.textView.attributedText = string;
-
字体倾斜
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"很好玩的富文本"]; [string addAttribute:NSObliquenessAttributeName value:@(0.5) range:NSMakeRange(0, 7)]; self.textView.attributedText = string;
-
字体加粗
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"很好玩的富文本"]; [string addAttribute:NSExpansionAttributeName value:@(0.5) range:NSMakeRange(4, 3)]; self.textView.attributedText = string;
-
加下划线并设置下划线颜色
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"很好玩的富文本"]; [string addAttribute:NSUnderlineStyleAttributeName value:@(1) range:NSMakeRange(4, 3)]; [string addAttribute:NSUnderlineColorAttributeName value:[UIColor blueColor] range:NSMakeRange(4, 3)]; self.textView.attributedText = string;
-
加删除线并设置删除线颜色
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"原价666