I'm trying to create custom data detectors for content in a UITextView. I'd like to be able to do something like this:
tv.dataDetectorTypes = UIDataDetectorTypeAll;
but instead of UIDataDetectorTypeAll, I want to use my custom UIDataDetector based on the following regular expression:
NSError *error = nil;
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"(ID: [0-9]+)"
options:NSRegularExpressionCaseInsensitive
error:&error];
I also would like the detected ID to be a link which pushes a UIWebView with a URL + ID combo ( http://www.stack.com?id ) to the nav stack. There should only ever be one id. Any ideas?
Thanks!
This took me all day and I finally found and modified this Ray Wenderlich solution. Apparently this, is a pretty obscure, new feature in iOS 7.
- (NSAttributedString *)makeAttributedAbstract:(NSString*)str
{
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:str];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(PMID: [0-9]+)" options:kNilOptions error:nil];
NSRange range = NSMakeRange(0, str.length);
[regex enumerateMatchesInString:str options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange subStringRange = [result rangeAtIndex:1];
[mutableAttributedString addAttribute:NSLinkAttributeName value:@"pmid://" range:subStringRange];
}];
return (NSAttributedString*)mutableAttributedString;
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"pmid"]) {
NSString *pmid = [NSString stringWithFormat:@"http://www.ncbi.nlm.nih.gov/pubmed/%@", [self.sql getPmidForId:self.abstractId] ];
NSURL *url = [NSURL URLWithString:pmid];
NSLog(@"pmid: %@", url);
[self pushWebViewWithURL:url];
return NO;
}
return YES; // let the system open this URL
}
http://www.raywenderlich.com/48001/easily-overlooked-new-features-ios-7#textViewLinks
I think you have to work around this problem because NSDataDetector is limited to the presets.
Look at this answer https://stackoverflow.com/a/19397842/2085504
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.