我正在开发聊天应用程序,如果输入的文本是 URL,则必须在其中检测到输入的文本。如果是这样,请更改其颜色并在其下划线。请看下面的截图:
要更改网址的颜色,我使用了以下代码:
NSString *urlString = [[detetctedURL absoluteString] stringByRemovingPercentEncoding];
/* *detetctedURL is detected url from entered text using NSDataDetector
/* *for messageText http://stackoverflow.com/somefolder/any-[thing]-etc, the detectedURL is http://stackoverflow.com/somefolder/any-%5Bthing%5B-etc */
NSRange r = [messageText rangeOfString:urlString];
if (r.location != NSNotFound)
{
//colorFromHex 4285f4
[atext addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:66.0/255.0 green:133.0/255.0 blue:244.0/255.0 alpha:1.0] range:r];
[atext addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:r];
//set attributed text (atext) to UILabel
}
如果 messageText 包含带有特殊字符和百分比编码的 URL,或者只有百分比编码,我如何正确格式化检测到的 URL?
谢谢!
更新 :
在以下代码的帮助下,我能够获得所需的范围。但是,对于大多数链接来说,它几乎可以正常工作,但并非所有链接都像存在']-('等字符的情况。
NSString *urlString = [url absoluteString];
NSRange r = [messageText rangeOfString:urlString];
BOOL foundRange = YES;
if (r.location == NSNotFound)
{
foundRange = NO;
//for umlauts or special characters
urlString = [[url absoluteString] stringByRemovingPercentEncoding];
r = [messageText rangeOfString:urlString];
if (r.location == NSNotFound)
{
//for white space in url
urlString = [urlString stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
r = [messageText rangeOfString:urlString];
if (r.location == NSNotFound)
{
urlString = [url absoluteString];
NSString *prefix = url.scheme;
if(prefix)
{
prefix = [prefix stringByAppendingString:@"://"];
urlString = [urlString stringByReplacingOccurrencesOfString:prefix withString:@""];
r = [messageText rangeOfString:urlString];
if (r.location == NSNotFound)
{
urlString = [urlString stringByRemovingPercentEncoding];
r = [messageText rangeOfString:urlString];
if (r.location == NSNotFound)
{
urlString = [urlString stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
r = [messageText rangeOfString:urlString];
if (r.location != NSNotFound){ foundRange = YES; }
}else{ foundRange = YES; }
}else{ foundRange = YES; }
}
}else{ foundRange = YES; }
}else{ foundRange = YES; }
}
if (foundRange)
{
//colorFromHex 4285f4
[atext addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:66.0/255.0 green:133.0/255.0 blue:244.0/255.0 alpha:1.0] range:r];
[atext addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:r];
myLabel.attributedText = atext;
}