我需要TTTAttributedLabel
点击部分的文字:
// initialize
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
// Attributed Message Label
NSMutableAttributedString *messageTextAttr =[row valueForKey:@"message_text_attr"];
cell.messageText.attributedText = messageTextAttr;
cell.messageText.delegate = self;
[messageTextAttr enumerateAttribute:NSLinkAttributeName inRange:NSMakeRange(0, messageTextAttr.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value) {
[cell.messageText addLinkToURL:[NSURL URLWithString:value] withRange:range];
}
}];
...
}
// click event
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
NSLog(@"link %@", [url absoluteString]);
NSLog(@"whole label %@", label);
}
但我只有链接和整个标签,但没有点击的部分(单击的文本部分)。我怎么能得到它?
答案 0 :(得分:4)
我能想到的唯一解决方案是实施attributedLabel: didSelectLinkWithTextCheckingResult:
而不是attributedLabel: didSelectLinkWithURL:
。
它的好处是,NSTextCheckingResult
包含范围属性,您可以使用该属性查找单击的实际文本(而不是URL)。
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTextCheckingResult:(NSTextCheckingResult *)result {
NSString* textClicked = [label.text substringWithRange:result.range];
//Get the URL and perform further actions
NSURL* urlClicked = result.URL;
}
答案 1 :(得分:0)
快速4 代码段
func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith result: NSTextCheckingResult!) {
guard let checkingResult = result else { return }
guard let clickedURL = checkingResult.url else { return }
guard let text = label.text as? NSString else { return }
let clickedText = text.substring(with: checkingResult.range)
}