在UILabel的NSAttributedString中創建可點擊的“鏈接”?我已經找了好幾個小時了,但我失敗了。我可能都不知道該找什么了。許多應用程序都有文本,在這篇文章中,Web超鏈接是四舍五入的RECT。當我點擊它們UIWebView打開。令我困惑的是,它們通常都有自定義鏈接,例如,如果單詞以#開頭,它也是可點擊的,應用程序通過打開另一個視圖來響應。我怎么能這么做?有沒有可能UILabel還是我需要UITextView還是別的什么?
3 回答

ibeautiful
TA貢獻1993條經驗 獲得超6個贊
更改部分文本的外觀,使其看起來像鏈接 檢測和處理鏈接上的觸摸(打開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 關注
- 3057 瀏覽
添加回答
舉報
0/150
提交
取消