我有textview,当用户键入链接时,应该更改颜色。我尝试了以下内容,
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].location != NSNotFound) {
NSString *stringWithNSDataDetector = [textView text];
NSError *error = nil;
NSDataDetector * dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink
error:&error];
UIFont *fontNormal = [UIFont fontWithName:@"SFUIText-Light" size:18.0];
__block NSMutableArray *allMatches = [[NSMutableArray alloc] init];
[dataDetector enumerateMatchesInString:stringWithNSDataDetector
options:0
range:NSMakeRange(0, [stringWithNSDataDetector length])
usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop)
{
if ([match resultType] == NSTextCheckingTypeLink){
[allMatches addObject:[match URL]];
NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:[[match URL] absoluteString]attributes:nil];
NSRange rangeOfUrl = NSMakeRange(0, [attributedString string].length);
[attributedString addAttribute:NSFontAttributeName value:fontNormal range:rangeOfUrl];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorFromHexString:TEXT_FIELD_UNDERLINE_BLUE] range:rangeOfUrl];
NSMutableAttributedString *finalizedStr = [[NSMutableAttributedString alloc]initWithString:self.postTxtView.text];
[finalizedStr replaceCharactersInRange:rangeOfUrl withAttributedString:attributedString];
self.postTxtView.attributedText = finalizedStr;
}
}];
for (NSURL *url in allMatches) {
NSLog(@"%@", [url absoluteString]);
}
}
return YES;
}
这个正在努力寻找链接。但是一旦找到链接并按下空格按钮,只有该链接应该是彩色的。
我该如何解决这个问题?
答案 0 :(得分:0)
如果您自己进行更换,则应返回NO,以便来电者也不会进行更换。
答案 1 :(得分:0)
看看你的代码:
NSRange rangeOfUrl = NSMakeRange(0, [attributedString string].length);
NSMutableAttributedString *finalizedStr = [[NSMutableAttributedString alloc]initWithString:self.postTxtView.text];
[finalizedStr replaceCharactersInRange:rangeOfUrl withAttributedString:attributedString];
self.postTxtView.attributedText = finalizedStr;
因此第一行以location
零的范围开始 - 即字符串的开头。然后,您将在该范围内插入属性字符串 - 即,在字符串的开头。然后,您将整个文本视图文本替换为该文本,因此彩色URL显示在文本的开头。