华山论剑之浅谈iOS文字印章的实现(NSMutableAttri
2016-08-02 本文已影响794人
神经骚栋
夫人之相与,俯仰一世,或取诸怀抱,悟言一室之内;或因寄所托,放浪形骸之外。虽趣舍万殊,静躁不同,当其欣于所遇,暂得于己,快然自足,曾不知老之将至。及其所之既倦,情随事迁,感慨系之矣。

前言
上面的一张图想必大家都不会陌生,没错,这就是王羲之的<<兰亭集序>>,你会问到,你一个程序猿搞什么<<兰亭集序>>干嘛,准备学习书法,陶冶情操.你还别说,你真说对了,我就是想陶冶情操,怀念古人遗风.😁😁😁
好了,言归正传,今天的主题就是如何在App文字的末尾加上印章如同上面的<<兰亭集序>>展示的效果?文字的展现好说,背景也好说,但是这个文字加印章的效果该如何实现呢?这就用到了NSMutableAttributedString和NSTextAttachment这两个类.
NSMutableAttributedString的简介
NSMutableAttributedString是继承于NSAttributedString,这个类是一个主要可以对文字的颜色、下划线等诸多属性进行修改的字符串类.他是实现富文本的一种方式.下面看看这个类所具有的属性和方法.
常见的属性及说明
NSFontAttributeName 字体
NSParagraphStyleAttributeName 段落格式
NSForegroundColorAttributeName 字体颜色
NSBackgroundColorAttributeName 背景颜色
NSStrikethroughStyleAttributeName删除线格式
NSUnderlineStyleAttributeName 下划线格式
NSStrokeColorAttributeName 删除线颜色
NSStrokeWidthAttributeName删除线宽度
NSShadowAttributeName 阴影
所具有的对象方法以及解释说明
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
为某一范围内文字设置多个属性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
为某一范围内文字添加某个属性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
为某一范围内文字添加多个属性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
移除某范围内的某个属性
NSTextAttachment的简介
NSTextAttachment是iOS7新增的类,作为文本的附件,可以放文件,可以放数据,所以是图文混编实现的一个重要的类.
文字印章的代码实现.
整个代码流程我是写在ViewController里面了,在Main.storyboard中添加一个UITextField和一个UILabel.然后直接监控输入框输入文字的变化并且使用NSMutableAttributedString和NSTextAttachment实现了图文混编.
实现代码如下
#import "ViewController.h"
@interface ViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *textField;//输入框
@property (strong, nonatomic) IBOutlet UILabel *showLabel;//展示Label
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textField.delegate = self;
}
//实时监控textField的值的变化,并赋值给Lable
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//使用可变的AttributedString接受TextField的字符串.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:textField.text];
//设置字体的大小
[attributedString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30]} range:NSMakeRange(0, textField.text.length)];
//创建textAttachment存放图片
NSTextAttachment *textAttachment = [[NSTextAttachment alloc]init];
//textAttachment的属性设置
textAttachment.image = [UIImage imageNamed:@"标签.png"];
textAttachment.bounds = CGRectMake(-10, -12, 160 , 40);
NSAttributedString *imgString = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString appendAttributedString:imgString];
self.showLabel.attributedText = attributedString;
return YES;
}
@end
演示效果如下.

因为实现代码的注释很详细,所以就不过多的作解释了.要想实现富文本,很多的技术点要进行学习,这次只是简单的对NSMutableAttributedString和NSTextAttachment实现图文混编做了初次的尝试,同时在此感谢阳哥的技术支持.谢谢.最后老规矩,Demo双手奉上.