2012-01-04 28 views
10

He utilizado "Regístrese usted mismo" como texto. Quiero hacerlo como un enlace. Y haciendo clic en ese enlace, debería abrir Register.xib.Para hacer que la etiqueta texto como enlace

¿Cómo puedo obtener este enlace?

+0

no puede entender su significado. ¿Quiere decir cómo hacer un hipervínculo en el texto, luego cuando se hace clic en él, ir a la vista de Registrarse? – Raptor

+5

Es mejor usar el botón UI de tipo personalizado en lugar de lablel. –

+0

Suena así. http://stackoverflow.com/questions/4743457/how-to-customize-uilabel-clickable – Ilanchezhian

Respuesta

12

Kareem tiene razón. Cree un objeto UIButton, establezca su tipo en "Personalizado" y luego puede darle un título. Conecte la acción a un método que presione o presente su controlador de vista de Registro y estará todo listo.

Probablemente le convenga indicar al usuario que el texto es un enlace en el que se puede hacer clic. Establezca el color del texto en azul. Otra opción, completamente separada, es usar NSAttributedString (que tiene un atributo de subrayado) para indicar al usuario que se puede hacer clic en el texto. Eso requiere an Open Source replacement for UITextView (que puede obtener más información acerca de this related question).

+0

Hola a todos, Kareem, Michael, muchas gracias .... pero tengo otra consulta que no pude encontrar ningún método para indicar al usuario que se puede hacer clic en el texto, es decir, tener un color azul de texto. Otra cosa, ¿puedo tener el símbolo de "mano" cuando el usuario mueve el cursor sobre esa cuerda ... ??? – Krunal

+0

Creo que está solicitando la aplicación iphone y la aplicación iphone no mostrará ningún cursor en la pantalla, ¿verdad? – DivineDesert

+0

Oopss ... sí, lo tengo ... – Krunal

0

Primero, construya la cadena atribuida y guarde el rango del texto interactivo y el texto mismo.

Luego, dibuje la cadena atribuida con CoreText Framework, mantenga el CTFrameRef.

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString); 
CGMutablePathRef path = CGPathCreateMutable(); 
CGPathAddRect(path, NULL, bounds); 

CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); 
CFRelease(framesetter); 

CTFrameDraw(frame, context); 
//CFRelease(frame); 

CGPathRelease(path); 

La última, anular el [ver touchesEnded: (NSSet *) toca withEvent: (UIEvent *) evento] como esto:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    NSSet *allTouches = [event allTouches]; 
    if ([allTouches count] == 1) { 
     UITouch *touch = (UITouch *)[allTouches anyObject]; 
     CGPoint touchPoint = [touch locationInView:self]; 

     // Convert to coordinate system of current view 
     touchPoint.y -= self.bounds.size.height; 
     touchPoint.y *= -1; 

     CGPathRef statusPath = CTFrameGetPath(statusCTFrame); 
     NSString *touchedInterStr = nil; 
     if (CGPathContainsPoint(statusPath, NULL, touchPoint, FALSE)) { 
      touchedInterStr = [self getInteractiveStringInFrame:statusCTFrame atPosition:touchPoint]; 
     } else { 
      return ; 
     } 
    } 
} 

- (NSString *)getInteractiveStringInFrame:(CTFrameRef)frame atPosition:(CGPoint)point 
{ 
    CGPathRef path = CTFrameGetPath(frame); 
    CGRect rect; 
    CGPathIsRect(path, &rect); 

    // Convert point into rect of current frame, to accurately perform hit testing on CTLine 
    CGPoint pointInsideRect = point; 
    pointInsideRect.x = point.x - rect.origin.x; 

    CFArrayRef lines = CTFrameGetLines(statusCTFrame); 
    CFIndex count = CFArrayGetCount(lines); 
    CGFloat curUpBound = rect.origin.y + rect.size.height; 
    CFIndex touchedIndex = -1; 
    for (CFIndex pos = 0; pos < count; pos++) { 
     CTLineRef curLine = CFArrayGetValueAtIndex(lines, pos); 
     CGFloat ascent, descent, leading; 
     CTLineGetTypographicBounds(curLine, &ascent, &descent, &leading); 
     CGFloat curHeight = ascent + descent + leading; 
     if (pointInsideRect.y >= curUpBound-curHeight && pointInsideRect.y <= curUpBound){ 
      touchedIndex = CTLineGetStringIndexForPosition(curLine, pointInsideRect); // Hit testing 
      break; 
     } 
     curUpBound -= curHeight; 
    } 
    if (touchedIndex == -1) 
     return nil; 

    NSEnumerator *enumerator = [interactiveStrs objectEnumerator]; 
    InteractiveString *curString; 
    while ((curString = (InteractiveString *)[enumerator nextObject])) { 
     if (NSLocationInRange(touchedIndex, curString.range)) { 
      return curString.content; 
     } 
    } 

    return nil; 
} 

Usted obtener el texto interactivo en touchesEnded, entonces se podría haz lo que quieras, como activar un método delegado.

PD: esta es la solución de la vieja usanza, escuché que iOS5 había proporcionado algo así como una UIWebView mejorada para implementar los requisitos, tal vez podría consultar la biblioteca de documentos de apple sdk.

+0

¿Qué es "InteractiveString"? No lo encontré .... –

2

creo que por debajo de usted obtendrá lo que desea ...

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    NSSet *allTouches = [event allTouches]; 
    if ([allTouches count] == 1) 
    { 
     UITouch *touch = (UITouch *)[allTouches anyObject]; 
     CGPoint touchPoint = [touch locationInView:self]; 

     // Convert to coordinate system of current view 
     touchPoint.y -= self.bounds.size.height; 
     touchPoint.y *= -1; 

     CGPathRef statusPath = CTFrameGetPath(statusCTFrame); 
     NSString *touchedInterStr = nil; 
     if (CGPathContainsPoint(statusPath, NULL, touchPoint, FALSE)) 
     { 
      touchedInterStr = [self getInteractiveStringInFrame:statusCTFrameatPosition:touchPoint]; 
     } 
     else 
     { 
      return ; 
     } 
    } 
} 
2

Hay un punto medio que es digno de mención. Usar UIButton con UIButtonTypeCustom tiene algunas deficiencias, a saber, que tienes un control limitado sobre el estilo del texto (por ejemplo, no puedes alinearlo a la derecha o a la izquierda, siempre estará centrado).

Usando NSAttributedString puede ser excesiva, y difícil de implementar si no está familiarizado con NSAttributedString, etc. CoreText

Una solución que he usado es un simple subclase de UIControl que permite una mayor personalización de la subclasificación UIButton y menos molestia que NSAttributedString et al. El enfoque UIControl solo es apropiado si toda la cadena será un "enlace".

Se podría hacer algo como esto en su UIControl subclase:

  • Añadir una subvista UILabel en el método init
  • Configurar el UILabel con su deseada backgroundColor, textColor, textAlignment etc, incluyendo cambios en el UILabel capa si desea que el fondo aparezca como los enlaces in-tweet de Twitter en su aplicación iOS
  • Anule el método setHighlighted: para personalizar el aspecto d sentir cambios en el tacto/seguimiento
  • Añadir @property set en el archivo .h por lo que la clase dominante puede establecer el estado
0

Tome un botón y establecer el título del botón que desea establecer como hipervínculo de texto. Puede elegir el botón de tipo de botón predeterminado y personalizado en iOS 7 e iOS 8, pero para el siguiente iOS 7 solo tiene que tomar el tipo de botón personalizado. Puede cambiar el color del texto para resaltar el texto de la interfaz de usuario y luego agregar cualquier acción que desee agregar en ese botón. Funcionará como encanto, buena suerte.

Cuestiones relacionadas