用户粘贴的链接很长,包含“http://”等,因此我想限制链接的长度,只显示主网站名称或更多。
例子:
用户粘贴的链接:
我想在标签中显示的链接:www.androidpolice.com/2015/08/...
有什么办法吗?
我搜索并找到了一个名为 attributesTruncationToken 但我不太了解的东西,我认为它与行尾的截断有关。
用户粘贴的链接很长,包含“http://”等,因此我想限制链接的长度,只显示主网站名称或更多。
例子:
用户粘贴的链接:
我想在标签中显示的链接:www.androidpolice.com/2015/08/...
有什么办法吗?
我搜索并找到了一个名为 attributesTruncationToken 但我不太了解的东西,我认为它与行尾的截断有关。
我不使用 TTTAttributeLabel 但这个答案适用于所有正在努力创建没有 3rd 方 API 的 URL 缩短器的问题寻求者。
只需使用 aNSMutableAttributedString
并传入一个UIDataDetectorTypeLink
有能力的对象:
假设您的用户输入了一个链接或完全传递了一个字符串:
我是用户。我想输入这个 URL 以分享给所有其他很棒的 Apple 产品用户,并且只分享给 Apple 产品 :)。在此处查看我的链接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;
}