检测NSAttributedString中链接的分接头

我正在使用drawInRect:动态构建视图并在其上打印属性文本。 一些文本可能包括Web链接。 如何检测Web链接上的点击,以便我可以在UIWebView中加载链接? 我没有使用UILabel,UITextView或UITextField来显示文本,因为文本包含文本和图像的混合。

这是drawRect中用于绘制文本的UIView子类的一些代码。

//draw the text NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:self.message.text]; [attString beginEditing]; NSArray *arrString = [attString.string componentsSeparatedByString:@" "]; for (NSString *str in arrString) { if ([str rangeOfString:@"http://" options:NSCaseInsensitiveSearch].location != NSNotFound || [str rangeOfString:@".com" options:NSCaseInsensitiveSearch].location != NSNotFound || [str rangeOfString:@".gov" options:NSCaseInsensitiveSearch].location != NSNotFound || [str rangeOfString:@".org" options:NSCaseInsensitiveSearch].location != NSNotFound || [str rangeOfString:@".edu" options:NSCaseInsensitiveSearch].location != NSNotFound || [str rangeOfString:@".net" options:NSCaseInsensitiveSearch].location != NSNotFound || [str rangeOfString:@".xxx" options:NSCaseInsensitiveSearch].location != NSNotFound) { NSRange rng = [attString.string rangeOfString:str]; NSString *url; if ([str rangeOfString:@"http://" options:NSCaseInsensitiveSearch].location == NSNotFound && [str rangeOfString:@"https://" options:NSCaseInsensitiveSearch].location == NSNotFound) { url = [NSString stringWithFormat:@"http://%@", str]; } else { url = str; } [attString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:url] range:rng]; } } [attString endEditing]; CGSize theSize; theSize = [attString.string sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(CHAT_TEXT_WIDTH, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping]; [[UIColor blackColor] set]; CGRect textRect = CGRectMake(0, 0, theSize.width, theSize.height); textRect.origin.x += 10; textRect.origin.y += 10; if (self.type == MESSAGE_BOX_RECEIVE) { textRect.origin.x += ARROW_WIDTH; } [attString drawInRect:textRect]; 

谢谢你的帮助…

你想要做的是用TextKit(在iOS 7中引入)绘制文本。 这允许您通过TextKit解释点击。

这是一个可下载的示例项目,我在其中显示单词列表并检测用户点击的单词(我甚至通过暂时突出显示单词来回复):

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch10p543drawingWithTextKit/ch23p815attributedStringDrawing3/StyledText.swift