如何减少链接的长度或为 TTTAttributedLabel 中检测到的链接设置固定长度

How to reduce length of links OR set a fixed length for links detected in TTTAttributedLabel

用户粘贴的链接很长,包含 "http://" 等,因此我想限制链接的长度,只显示主要网站名称或更多。

示例:

Link 用户粘贴:

http://www.androidpolice.com/2015/08/16/an-alleged-leak-of-lgs-nexus-5-2015-bullhead-pops-up-on-google/

Link我要在标签中显示:www.androidpolice.com/2015/08/...

有什么办法吗?

我搜索并找到了一个名为 attributedTruncationToken 的东西,但我不太了解,我认为它与行尾截断有关。

我不使用 TTTAttributeLabel,但 此答案适用于所有未来正在努力创建没有第 3 方 API 的 URL 缩短器的问题寻求者。

只需使用 NSMutableAttributedString 并传入 UIDataDetectorTypeLink 可用对象:

假设您的用户输入 link 或完整传递一个字符串:

I am a user. I want to enter this URL to share to all other awesome users of Apple products, and only Apple products :). Check out my link here http://www.androidpolice.com/2015/08/16/an-alleged-leak-of-lgs-nexus-5-2015-bullhead-pops-up-on-google/

我们可以使用常用的方法轻松提取文本:

NSString *userInput = @"I am a user. I want to enter this URL to share to all other awesome users of Apple products, and only Apple products :). Check out my link here http://www.androidpolice.com/2015/08/16/an-alleged-leak-of-lgs-nexus-5-2015-bullhead-pops-up-on-google/"

// get the range of the substring (url) starting with @"http://"
NSRange httpRange = [userInput rangeOfString:@"http://" options:NSCaseInsensitiveSearch];

if (httpRange.location == NSNotFound) {
    NSLog(@"URL not found");
} else {
    //Get the new string from the range we just found
    NSString *urlString = [userInput substringFromIndex:httpRange.location];
    //create the new url
    NSURL *newURL = [NSURL URLWithString:urlString];
    //cut off the last components of the string
    NSString *shortenedName = [urlString stringByDeletingLastPathComponent];
    //new output
    NSLog(@"%@", [NSString stringWithFormat:@"\n original user input : \n %@ \n original URL name : \n %@ \n shortenedName : \n %@", userInput, urlString, shortenedName]);

    //We have everything we need so all we have remaining to do is create the attributes and pass into a UITextView. 
    self.someTextView.attributedText = [self createHyperLinkForURL:newURL withName:shortenedName];
}

哪里[self createHyperLinkForURL:newURL withName:shortenedName];

-(NSMutableAttributedString *)createHyperLinkForURL:(NSURL *)url withName:(NSString *)hyperLinkText {
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:hyperLinkText];
    [string beginEditing];
    [string addAttribute:NSLinkAttributeName
               value:url
               range:NSMakeRange(0, string.length)];
    [string endEditing];
    return string;
}