- ( void )viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//创建一个矩形区域
CGRect textViewRect=CGRectInset(self.view.bounds, 10.0, 20.0);
//创建NSTextStorage对象,它需要一个字符串作为构造方法的参数,这里我们是从TextView 控件取出来付值给它的
NSTextStorage *textStorage=[[NSTextStorage alloc] initWithString:self.textView.text];
NSLayoutManager *layoutManager=[[NSLayoutManager alloc] init];
//将刚创建的nstextStorage和NSLayoutManager对象关联起来
[textStorage addLayoutManager:layoutManager];
self.textContainer =[[NSTextContainer alloc] initWithSize:textViewRect.size];
//将NSLayoutManager和NSTextContainer关联起来
[layoutManager addTextContainer:self.textContainer];
/**
*重新构建原来的TextView控件,并且重新添加到视图上。这主要是因为只有重新创建代码
*才能通过Text Kit中NSLayoutManager来管理,而原来在Interface Builder中创建的TextView控件不*能使用了
*/
[self.textView removeFromSuperview];
self.textView=[[UITextView alloc] initWithFrame:textViewRect textContainer:_textContainer];
// [self.view addSubview:self.textView];
[self.textView setFont:[UIFont systemFontOfSize:20.0f]];
//添加的textView在ImageView之下
[self.view insertSubview:self.textView belowSubview:self.imageView];
//设置凸版印刷效果
[textStorage beginEditing];
/**
*声明一个字典对象,其中包括@{NSTextEffectAttribute-*Name:NSTextEffectLetterpressStyle},NSTextEffectAttributeName是文本效果建,而*NSTextEffect- LetterpressStyle是文本效果值,这里面它们都是常量
*/
NSDictionary *attrsDic = @{NSTextEffectAttributeName: NSTextEffectLetterpressStyle};
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:_textView.text attributes:attrsDic];
[textStorage setAttributedString:attrStr];
[self markWord:@ '我' inTextStorage:textStorage];
[self markWord:@ 'N' inTextStorage:textStorage];
[textStorage endEditing];
self.textView.textContainer.exclusionPaths=@[[self translatedBezierPath]]; //设置translatedBezierPath方法
}
//改变textview和imageView的坐标
- (UIBezierPath *)translatedBezierPath
{
CGRect imageRect = [self.textView convertRect:_imageView.frame fromView:self.view]; UIBezierPath *newPath = [UIBezierPath bezierPathWithRect:imageRect];
return newPath;
}
//根据指定的文本设置样式风格
-( void )markWord:(NSString *)word inTextStorage:(NSTextStorage *)textStorage{
//
NSRegularExpression *regex=[NSRegularExpression regularExpressionWithPattern:word options:0 error:nil];
//通过正则表达式NSRegularExpression对象对TextView中的文本内 容进行扫描,结果放到数组中
NSArray *matches=[regex matchesInString:self.textView.text options:0 range:NSMakeRange(0, [self.textView.text length])];
//为找到的文本设置颜色
for (NSTextCheckingResult *match in matches) {
NSRange matchRange=[match range];
[textStorage addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:matchRange];
}
}
|