问题

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?
回答1:
As per my understanding you can UItextview and its delegate will help.
Step 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;
}
Step 2 Add delegate
-(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;
}
Step 3 Editable (No),Selectable (Yes), Links is optional

Hope it will help you..!
回答2:
you can use html string in attribute string like this:
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
回答3:
Use UITextView
it is easy to implement. Add tap gesture on textview and when tap on textview check if tap on specific character or not.
textView.textContainerInset = UIEdgeInsetsZero;
[textView setContentInset:UIEdgeInsetsZero];
textView.attributedText = @"your attributedString";
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textTapped:)];
[textView addGestureRecognizer:tap];
Add Gesture implementation method
- (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:");
}
}
来源:https://stackoverflow.com/questions/28472073/can-i-get-the-position-of-elements-in-nsattributedstring