您可以使用標準的標籤和HTML創建屬性串,那麼你必須在你的標籤鏈接
let label = UILabel()
let attributedText = try? NSAttributedString(data: <your string>.data(using: .utf8)!, options:
[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 ],
documentAttributes: nil)
//接下來會OBJC
NSMutableAttributedString *mutableText = [[NSMutableAttributedString alloc] initWithAttributedString:attributedText];
self.textContainer = [[NSTextContainer alloc] initWithSize:self.label.bounds.size];
self.textContainer.lineFragmentPadding = 0;
self.textContainer.maximumNumberOfLines = self.label.numberOfLines;
self.textContainer.lineBreakMode = self.label.lineBreakMode;
self.layoutManager = [NSLayoutManager new];
[self.layoutManager addTextContainer:self.textContainer];
self.textStorage = [[NSTextStorage alloc] initWithAttributedString:self.label.attributedText];
[self.textStorage addLayoutManager:self.layoutManager];
在一個屬性串,帶鏈接的文本範圍將具有屬性NSLinkAttributeName
。您可以在該屬性上覆蓋enumerateAttribute
,併爲該屬性的每個範圍添加您自己的字體和顏色,從該範圍中刪除該NSLinkAttributeName
,然後添加MYLinkAttributeName
屬性。
[attributedText enumerateAttribute:NSLinkAttributeName inRange:NSMakeRange(0, attributedText.length) options:kNilOptions usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (nil != value)
{
[mutableText addAttribute:NSStrokeColorAttributeName value:greenColor range:range];
[mutableText addAttribute:NSForegroundColorAttributeName value:greenColor range:range];
[mutableText addAttribute:MYLinkAttributeName value:value range:range];
[mutableText removeAttribute:NSLinkAttributeName range:range];
}
}];
此後,在標籤上添加UITapGestureRecognizer
並執行其delegate
回調
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
self.textContainer.size = self.label.bounds.size;
NSUInteger index = [self.layoutManager characterIndexForPoint:[touch locationInView:self.label]
inTextContainer:self.textContainer
fractionOfDistanceBetweenInsertionPoints:NULL];
self.lastTouchedLinkAttributeValue = [self.label.attributedText attribute:MYLinkAttributeName atIndex:index effectiveRange:NULL];
return nil != self.lastTouchedLinkAttributeValue;
}
最後,識別動作:
- (IBAction)tapRegognized:(id)sender
{
// Here value of 'href' is stored in self.lastTouchedLinkAttributeValue as NSURL instance.
}
沒錯,但問題是,我已經應用了字體和顏色屬性添加到段落文本中,我無法將這個額外的鏈接屬性應用於AttributedString。我不知道如何將一個額外的屬性應用於現有的attributes。 – Rao
查看更新的答案,我在ObjC中有過 – DisableR