用户粘贴的链接很长并且包含“http://”等因此我想限制链接的长度并仅显示主网站名称或稍多一点。
示例:
用户粘贴的链接:
链接我想在标签中显示:www.androidpolice.com/2015/08 / ...
有什么办法吗?
我搜索并找到了一个名为attributionTruncationToken的东西,但我不太懂,我认为它与行尾的截断有关。
答案 0 :(得分:0)
我不使用TTTAttributeLabel,但这个答案适用于所有未来的问题搜索者,他们正在努力创建没有第三方API的URL缩短器。
只需使用NSMutableAttributedString
并传递到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;
}