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

问题描述:

我使用 NSAttributeString 得到类似上面的东西(包括普通文本、带下划线的文本和图像),现在我想做:如果用户点击带下划线的文本区域,我会做一些特殊的动作(打开网页或……).现在我已经可以得到触摸的位置了,但是我能找到带下划线的文本的位置(或区域)吗?所以我可以同时使用两个区域来判断点击位置是否位于下划线文本上?

I use NSAttributeString to get something like above(include normal text ,underlined text and images) , and now I want do : if the user tapped on the underlined text area , I will do some special actions (open the web or sth). Now i can get the location of touches already , but can i find the locations (or area) of the underlined text ? so I can use both area to judge the tap position is located on underline text or not?

根据我的理解,您可以使用 UItextview 及其代理.

As per my understanding you can UItextview and its delegate will help.

第一步

{
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 步可编辑(否),可选择(是),链接是可选的

Step 3 Editable (No),Selectable (Yes), Links is optional

希望能帮到你..