2012-06-13 19 views
5

Actualmente estoy usando UITextView en un UITableViewCell para hacer que los enlaces se puedan hacer clic, pero esto está dando muy poco rendimiento.Detectar URL en NSString

Me preguntaba si es posible detectar enlaces en un NSString y si hay un enlace, use el UITextView, de lo contrario, simplemente use un UILabel.

+0

Puede ser que usted pueda verificar para 'http' en NSString, si contiene, entonces es un enlace. – rishi

+0

@rishi, el problema es que hay muchos tipos de URL, UITextView parece detectarlos a todos, por lo que google.com, www.google.com, ... –

Respuesta

14

Absolutamente. Utilice NSDataDetector (NSDataDetector Class Reference)

+0

Woah, eso funcionó perfectamente, así de fácil, use esto mismo "regex" como UITextView utiliza? –

+3

Otro artículo útil para esta API es http://www.nshipster.com/nsdatadetector/. – AdamG

2

supongo que está familiarizado con expresiones regulares para detectar direcciones URL, por lo que a fin de obtener uno u otro tipo de vista en su celda, simplemente puede devolver dos diferentes UITableViewCell s de su método de tableView:cellForRowAtIndexPath:.

Podría tener este aspecto (note por favor, escrito en el navegador no probado):

- (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

No estoy realmente familiarizado con las expresiones regulares, especialmente no en Object-C, de ahí la pregunta aquí –

+0

Gracias por el ejemplo, ¿habría una diferencia entre usar 2 celdas personalizadas, o simplemente usar una, pero agregar el UITextView y UILabel en y luego eliminar uno de ellos? –

+0

Sí, acabo de agregarlos en IB y los eliminé con código, en mi caso, tendría que hacer un control de todos modos para establecer la altura de la fila –

1

El uso de este recorte de código que sería capaz de encontrar y llegar url http en UILable usando 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)];