如果您还需要从 UITextView 中过滤一些单词并使其下划线/更改该特定文本的颜色,那么您可以使用下面的代码。
在这里,我得到了 Content 字符串中的所有文档文本,并过滤了一些希伯来语的特定文本。
NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc]initWithString:content attributes:nil];
[aStr addAttribute:NSLinkAttributeName value:@"http://www.apple.com" range:[content rangeOfString:@"מדיניות פרטיות"]];
[aStr addAttribute:NSLinkAttributeName value:@"http://www.google.com" range:[content rangeOfString:@"לינק"]];
textview.linkTextAttributes = @{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)};
textview.delegate = (id)self;
//...您可以根据您的自定义颜色
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[content rangeOfString:@"מדיניות פרטיות"]];
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[content rangeOfString:@"לינק"]];
//在这里您还可以在该文本上添加点击手势。//点击手势
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedTextView:)];
[textview addGestureRecognizer:tapRecognizer];
[textview setAttributedText:aStr];
textview.textAlignment=NSTextAlignmentRight;
//用于获取点击手势中的文本位置
-(void)tappedTextView:(UITapGestureRecognizer *)tapGesture
{
UITextView *textView = (UITextView *)tapGesture.view;
CGPoint tapLocation = [tapGesture locationInView:textView];
UITextPosition *textPosition = [textView closestPositionToPoint:tapLocation];
NSDictionary *attributes = [textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];
NSString *urlStr = attributes[NSLinkAttributeName];
if (urlStr)
{
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",url]]];
PrivacyViewController *next = [PrivacyViewController new];
[self.navigationController pushViewController:next animated:YES];
}
}