2012-06-13 13 views
5

Aktualnie używam UITextView w UITableViewCell, aby linki były klikalne, ale daje to bardzo niską wydajność.Wykryj adres URL w NSString

Więc zastanawiałem się, czy można wykryć linki w NSString i jeśli istnieje łącze, użyj UITextView, w przeciwnym razie po prostu użyj UILabel.

+0

Może to oznaczać "http" w NSString, jeśli zawiera, to jest link. – rishi

+0

@rishi, problem polega na tym, że istnieje wiele typów adresów URL, UITextView wydaje się je wszystkie wykrywać, więc google.com, www.google.com, ... –

Odpowiedz

14

Absolutnie. Użyj NSDataDetector (NSDataDetector Class Reference)

+0

Woah, to działało idealnie, tak łatwo, zrób to za pomocą same "regex" jak używa UITextView? –

+3

Innym przydatnym artykułem dla tego interfejsu API jest http://www.nshipster.com/nsdatadetector/. – AdamG

2

Chyba jesteście zaznajomieni z Wyrażenia regularne do wykrywania adresów URL, tak, aby uzyskać jeden lub drugi rodzaj widoku w swojej komórce, można po prostu wrócić dwa różne UITableViewCell s od wybranej metody tableView:cellForRowAtIndexPath:.

mogłoby to wyglądać tak (proszę zauważyć, wpisane w przeglądarce nie sprawdzone)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    NSString *dataString = // Get your string from the data model 

    // Simple pattern found here: http://regexlib.com/Search.aspx?k=URL 
    NSString *URLpattern = @"^http\\://[a-zA-Z0-9\-\.]+\\.[a-zA-Z]{2,3}(/\\S*)?$"; 

    NSError *error = NULL; 
    NSRegularExpression *URLregex = [NSRegularExpression regularExpressionWithPattern:URLpattern 
                       options:NSRegularExpressionCaseInsensitive 
                       error: &error]; 

    NSUInteger numberOfMatches = [URLregex numberOfMatchesInString:string 
                options:0 
                 range:NSMakeRange(0, [string length])]; 

    if (numberOfMatches == 0) { 
     static NSString *PlainCellIdentifier = @"PlainCellIdentifier"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
     if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; 
     } 
     cell.textLabel.text = timeZoneWrapper.localeName; 
    } 
    else { 
     static NSString *FancyCellIdentifier = @"FancyCellIdentifier"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
     if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; 
     } 

     // Configure cell view with text view here 
    } 

    return cell; 
} 
+1

Nie jestem zaznajomiony z wyrażeniami regularnymi, zwłaszcza nie w celu-c, stąd pytanie tutaj –

+0

Dzięki za przykład, będzie różnica między używaniem 2 niestandardowych komórek lub po prostu użyj jednego, ale dodaj UITextView i UILabel w to, a następnie usunąć jedną z nich? –

+0

Tak, właśnie dodałem je do IB i usunąłem je za pomocą kodu, w moim przypadku i tak musiałbym zrobić czek, aby ustawić wysokość wiersza –

1

Korzystanie z tej wycinek kodu będzie można znaleźć i dostać http url w UILable użyciu NSDataDetector:

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil]; 
       NSArray* matches = [detector matchesInString:yourString options:0 range:NSMakeRange(0, [yourString. length])]; 
       NSLog(@"%@",matches) ; 
       NSMutableAttributedString *MylabelAttributes = 
    [[NSMutableAttributedString alloc] initWithString:yourString]; 
       for (int index = 0 ; index < matches.count; index ++) { 
       NSTextCheckingResult *textResult = [matches objectAtIndex : index]; 
       NSTextCheckingType textResultType = textResult.resultType; 
       NSRange testRange = textResult.range; 
       NSURL *testUrl = textResult.URL ;} 

After applying this code, you will be able to attribute your `UILabel` text: 

    [MylabelAttributes addAttribute:NSLinkAttributeName value:testUrl range: testRange]; 
    [MylabelAttributes addAttribute:NSFontAttributeName      
    value:[UIFont boldSystemFontOfSize:7.0]range:NSMakeRange(0,yourString.length)];