我可以在NSAttributedString中获取元素的位置吗?

在这里输入图像说明

我使用NSAttributeString来获得像上面这样的东西(包括普通文本,带下划线的文本和图像),现在我想要做的事情是:如果用户点击加下划线的文本区域,我会做一些特殊的操作(打开网页或者某事)。 现在我可以得到触摸的位置,但我可以find加下划线的文本的位置(或区域)? 所以我可以使用这两个区域来判断分接位置是否位于下划线文字上?

根据我的理解你可以UItextview和它的委托将有所帮助。

步骤1

 { NSURL *URL = [NSURL URLWithString: @"http://www.sina.com"]; NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:"Your text to display"]; [str addAttribute: NSLinkAttributeName value:URL range: NSMakeRange(0, str.length)]; _textview.attributedText = str; } 

步骤2添加委托

 -(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { NSLog(@"URL:: %@",URL); //You can do anything with the URL here (like open in other web view). [[UIApplication sharedApplication] openURL:URL]; return YES; } 

步骤3可编辑(否),可选(是),链接是可选的

请从textview中勾选以下属性

希望它会帮助你..!

你可以像这样在属性string中使用htmlstring:

 NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 

使用UITextView很容易实现。 在文本视图上添加点击手势,当点击文本视图时,检查是否点击特定的字符。

 textView.textContainerInset = UIEdgeInsetsZero; [textView setContentInset:UIEdgeInsetsZero]; textView.attributedText = @"your attributedString"; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textTapped:)]; [textView addGestureRecognizer:tap]; 

添加手势实现方法

 - (void)textTapped:(UITapGestureRecognizer *)recognizer { UITextView *textView = (UITextView *)recognizer.view; /*--- Get range of string which is clickable ---*/ NSRange range = [textView.text rangeOfString:@"Your Clickable String"]; NSLayoutManager *layoutManager = textView.layoutManager; CGPoint location = [recognizer locationInView:textView]; NSUInteger characterIndex = [layoutManager characterIndexForPoint:location inTextContainer:textView.textContainer fractionOfDistanceBetweenInsertionPoints:NULL]; if (characterIndex >= range.location && characterIndex < range.location + range.length - 1) { NSLog(@"Text Tapped:"); } }