//检测uitextview 文本 获取 link
-(void)uiTextViewClick:(UITapGestureRecognizer*)tap{
if ([tap isKindOfClass:[UITapGestureRecognizer class]])
{
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:tap.view.tag+2];
EMGoodsCommentCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
NSLayoutManager *layoutManager = cell.lblContent.layoutManager;
CGPoint location = [tap locationInView:cell.lblContent];
location.x -= cell.lblContent.textContainerInset.left;
location.y -= cell.lblContent.textContainerInset.top;
//点击的字符索引
NSUInteger characterIndex = [layoutManager glyphIndexForPoint:location inTextContainer:cell.lblContent.textContainer];
CGRect glyphRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(characterIndex,1) inTextContainer:cell.lblContent.textContainer];
//EM示例 字符检测 判断是否点击的字符
if(CGRectContainsPoint(glyphRect,location))
{
//检测是否包含超级链接
CGPoint tapLocation = [tap locationInView:cell.lblContent];
UITextPosition* textPosit = [cell.lblContent closestPositionToPoint:tapLocation];
NSDictionary *attributes = [cell.lblContent textStylingAtPosition:textPosit inDirection:UITextStorageDirectionForward];
NSString *link = attributes[NSLinkAttributeName];
NSURL *url = [[NSURL alloc] initWithString:[[NSString stringWithFormat:@"%@",link] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
//点击的字符但是未点击link
if(link==nil)
{
//弹出评论回复窗口
[self commentWindow:indexPath];
}
if (characterIndex < cell.lblContent.textStorage.length) {
NSRange range;
//获取超级链接字符的索引
id value = [cell.lblContent.attributedText attribute:[url host] atIndex:characterIndex effectiveRange:&range];
//判断链接字符位置
if(characterIndex>=range.location&&characterIndex<=(range.location+range.length))
{
if(link)
{
if ([[url scheme] isEqualToString:@"callUser"]) {
EMMyHomeController* page = [[EMMyHomeController alloc] init];
id params = @{@"userId":[url query]};
[[PageManager shareInstance] gotoPage:page withParams:params];
}else if ([[url scheme] isEqualToString:@"talk"])
{
NSLog(@"跳转话题界面 未实现");
}
}
}
}
}
else
{
NSLog(@"点击空白处");
//弹出评论回复窗口
[self commentWindow:indexPath];
}
}
}
该代码段展示了如何在Objective-C中检测UITextView中的链接点击。当用户点击文本时,它会获取点击位置的字符索引,判断是否包含链接,并根据链接类型执行相应操作,如跳转页面或显示评论窗口。
1075

被折叠的 条评论
为什么被折叠?



