2017-10-06 49 views
0

我使用UITextView的委托方法textView:shouldInteractWithURL:inRange:interaction:来捕获URL点击。有什么方法可以确定哪个UIDataDetectorTypes触发了委托方法?确定哪个UITextView UIDataDetectorType被触发

我对电子邮件,电话号码,地址(地理位置),日期/时间等有不同的自定义方法。现在我可以看到的唯一方法是使用RegEx从使用“猜测” URL(这是非常无用的东西比HTTP/HTTPS URL)和经由

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction { 
    NSString *rawText = [textView.text substringWithRange:characterRange]; 
    // Do fancy stuff with the data 

    // Hacky way to test if the url tapped isn't an email/map address 
    BOOL isURL = [[URL absoluteString] isEqualToString:[textView.text substringWithRange:characterRange]]; 

    // Return no when the URL can be captured and custom methods used. Otherwise return YES. 
    return NO; 
} 

编辑拍了拍原始数据:我已经跨越NSDataDetector偶然发现它可以帮助,但我不知道从哪里开始

回答

0

我相信我已经找到了解决我的问题。我张贴我的答案,以便任何与此问题斗争的人都可以看到我做了什么(并且如果它不是很好,可能有助于改进我的代码)。

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction { 
    NSString *string = [textView.text substringWithRange:characterRange]; 
    if (string.length <= 0) { 
     return YES; 
    } 
    NSError *dataDetectorError = nil; 
    NSTextCheckingTypes dataCheckingTypes = NSTextCheckingTypeDate | NSTextCheckingTypeAddress | NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber; 
    NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes:dataCheckingTypes error:&dataDetectorError]; 
    if (!isNull(dataDetectorError)) { 
     NSLog(@"Data detector init error: %@", dataDetectorError.localizedDescription); 
     return YES; 
    } 

    [dataDetector enumerateMatchesInString:string 
            options:kNilOptions 
            range:NSMakeRange(0, string.length) 
           usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) { 
            if (!isNull(result)) { 
             // Now we get the result type 
             switch (result.resultType) { 
              case NSTextCheckingTypeDate: 
              case NSTextCheckingTypeAddress: 
              case NSTextCheckingTypeLink: 
               if([result.URL.absoluteString rangeOfString:@"mailto:"].location != NSNotFound) { 
                // email 
               } 
               else { 
                // url 
               } 
              case NSTextCheckingTypePhoneNumber: 
               break; 
              default: 
               // Ignore all other types 
               break; 
             } 
            } 
           } 
    ]; 
} 

显然,这是一个不完整的实现但它说明了如何使用内置的正则表达式的子类,以获得不同类型的

相关问题