我发了一个可点击的链接。我的代码:
NSString *textBlah = @"blah bleh bluh blih....";
- (void)hyperLinkAndColor:(NSString*)name withAttribute:(NSMutableAttributedString*)attributedText{
if ([textBlah rangeOfString:name].location != NSNotFound) {
NSRange rangeName = [textInformation rangeOfString:name];
if ([name rangeOfString:@" "].location != NSNotFound) {
name = [name stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
}
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"linktink://?name=%@", name]];
[attributedText beginEditing];
[attributedText addAttribute:NSLinkAttributeName value:[url absoluteString] range:rangeName];
[attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:rangeName];
[attributedText endEditing];
}
}
工作正常。但我得到一个问题。当'name'是您好或হ্যালো或héllò...时,url总是返回nil。如何检测您好或হ্যালো...并点击它?
答案 0 :(得分:0)
将代码修改为URL对字符串进行编码,以便unicode字符不会产生问题。
NSString *textBlah = @"blah bleh bluh blih....";
- (void)hyperLinkAndColor:(NSString*)name withAttribute:(NSMutableAttributedString*)attributedText{
if ([textBlah rangeOfString:name].location != NSNotFound) {
NSRange rangeName = [textInformation rangeOfString:name];
NSString *urlString = [NSString stringWithFormat:@"linktink://?name=%@", name];
NSURL* url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[attributedText beginEditing];
[attributedText addAttribute:NSLinkAttributeName value:[url absoluteString] range:rangeName];
[attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:rangeName];
[attributedText endEditing];
}
}