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

标签 ios objective-c uilabel nsattributedstring tttattributedlabel

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

例:

用户粘贴的链接:

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

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

有什么办法吗?

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

最佳答案

我不使用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;
}

关于ios - 如何减少链接长度或为在TTTAttributedLabel中检测到的链接设置固定长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32050729/

相关文章:

iphone - 低优先级长时间运行任务

ios - 在自定义 UICollectionViewCell 中更改 UILabel 的文本颜色

iOS:在文本 UILabel 周围绘制边框

iphone - iOS 导航面包屑路径

ios - 签署 apple-app-site-association

ios - didSelectRow 未很好地注册单元格触摸

iphone - 如何使用 ASIFormDataRequest 到 NSDictionary 对象的 http post 数组

iphone - 释放 CFString

ios - 根据 UIlabel IBDesignable 中的标题和副标题设置不同的字体

iphone - 检测 iOS 5 上的铃声(静音按钮)位置?