在UILabel的NSAttributedString中创建可点击的“链接”?我已经找了好几个小时了,但我失败了。我可能都不知道该找什么了。许多应用程序都有文本,在这篇文章中,Web超链接是四舍五入的RECT。当我点击它们UIWebView打开。令我困惑的是,它们通常都有自定义链接,例如,如果单词以#开头,它也是可点击的,应用程序通过打开另一个视图来响应。我怎么能这么做?有没有可能UILabel还是我需要UITextView还是别的什么?
3 回答
ibeautiful
TA贡献1993条经验 获得超5个赞
更改部分文本的外观,使其看起来像链接 检测和处理链接上的触摸(打开URL是一种特殊情况)
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"String with a link" attributes:nil]; NSRange linkRange = NSMakeRange(14, 4); // for the word "link" in the string aboveNSDictionary *linkAttributes = @{ NSForegroundColorAttributeName : [UIColor colorWithRed:0.05 green:0.4 blue:0.65 alpha:1.0], NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) }; [attributedString setAttributes:linkAttributes range:linkRange]; // Assign attributedText to UILabellabel.attributedText = attributedString;
label.userInteractionEnabled = YES;[label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget: self action:@selector(handleTapOnLabel:)]];
// Create instances of NSLayoutManager, NSTextContainer and NSTextStorageNSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];// Configure layoutManager and textStorage[layoutManager addTextContainer:textContainer]; [textStorage addLayoutManager:layoutManager];// Configure textContainertextContainer.lineFragmentPadding = 0.0;textContainer.lineBreakMode = label.lineBreakMode;textContainer.maximumNumberOfLines = label.numberOfLines;
- (void)viewDidLayoutSubviews{ [super viewDidLayoutSubviews]; self.textContainer.size = self.label.bounds.size;}
- (void)handleTapOnLabel:(UITapGestureRecognizer *)tapGesture{ CGPoint locationOfTouchInLabel = [tapGesture locationInView:tapGesture.view]; CGSize labelSize = tapGesture.view.bounds.size; CGRect textBoundingBox = [self.layoutManager usedRectForTextContainer:self.textContainer]; CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y); CGPoint locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x, locationOfTouchInLabel.y - textContainerOffset.y); NSInteger indexOfCharacter = [self.layoutManager characterIndexForPoint:locationOfTouchInTextContainer inTextContainer:self.textContainer fractionOfDistanceBetweenInsertionPoints:nil]; NSRange linkRange = NSMakeRange(14, 4); // it's better to save the range somewhere when it was originally used for marking link in attributed string if (NSLocationInRange(indexOfCharacter, linkRange)) { // Open an URL, or handle the tap on the link in any other way [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://stackoverflow.com/"]]; }}
- 3 回答
- 0 关注
- 2968 浏览
添加回答
举报
0/150
提交
取消