2012-10-08 13 views
6

Estoy tratando de crear un UILabel o UITextView con texto en negrita y normal dentro.¿Cómo crear un UILabel o UITextView con texto en negrita y normal en él?

He pasado por la cadena de atribución pero cuando configuro esto en la etiqueta de mi celda personalizada no muestra ningún texto.

También he usado el método UITextView setContentToHTMLString:, pero no está documentado y la aplicación es rechazada.

¿Alguien puede dar algún tipo de solución a esto?

+0

wow ... Nunca he visto una pregunta convertirse en una "wiki de la comunidad" (9 revisiones en cuestión de minutos) ¡tan rápido! –

+1

Todavía no entiendo por qué esta pregunta se convirtió a una wiki de la comunidad. – Krishnabhadra

Respuesta

5

Uso "NSAttributedString" para configurar múltiples texto fuente en una sola etiqueta & uso CATextLayer para hacerlo:

simplemente #import "NSAttributedString+Attributes.h"

y luego implementarla como este:

NSString *string1 = @"Hi"; 

NSString *string2 = @"How are you ?"; 

NSMutableAttributedString *attr1 = [NSMutableAttributedString attributedStringWithString:string1]; 

[attr1 setFont:[UIFont systemFontOfSize:20]]; 

NSMutableAttributedString *attr2 = [NSMutableAttributedString attributedStringWithString:string2] 

[attr2 setFont:[UIFont boldSystemFontOfSize:20]]; 

[attr1 appendAttributedString:attr2] 

CATextLayer *textLayer = [CATextLayer layer]; 

layer.string = attr1; 

layer.contentsScale = [[UIScreen mainScreen] scale]; 

(Your_text_label).layer = textLayer; 

OR (if you want to render on a view directly) 

[(Your_View_Name).layer addSublayer:textLayer]; 
5

Hasta iOS 6.0, no se podía hacer esto con un UILabel normal o UITextView, pero puede utilizar objetos NSAttributedString con algunas posibles soluciones de código abierto.

Me gusta TTAttributedLabel o OHAttributedLabel.

Una solución integrada en el SDK de iOS, you could also use a CATextLayer which has a string property that can be set to a NSAttributedString.

Y, como dicen los comentaristas a continuación, sí, puede hacerlo con el "attributedText" property. ¡Horray! (Para Apple escuchar las peticiones de características muy a menudo repetidas de los desarrolladores)

+0

Tenga en cuenta que UILabel es compatible con NSAttributedString con iOS 6. – Eiko

+0

Usted puede hacer esto con UILabels y UITextView normales desde iOS 6 usando la propiedad 'attributeText' –

+0

Estoy usando iOS 5 en adelante, ¿será compatible con iOS 5? – Rocker

1

Sé que este es un hilo viejo, pero esto es algo que acabo de descubrir. Al menos en Xcode versión 4.6.3 esto es posible mediante el uso de un textView atribuido. ¡Lo que es aún mejor es que todo se puede hacer en Interface Builder!

Estos son los pasos:

Coloque el Textview en el lugar deseado Seleccione el TextView y abrir la pestaña Atributos debajo del panel Utilidades Cambie el texto Textview a "atribuir" Introduzca el texto deseado Ahora , resalte el texto que desee en negrita, subrayado, etc. Haga clic en el botón "T" junto al fontName En la ventana emergente, seleccione el tipo de letra que desee (por ejemplo: Negrita) Debería ver el tipo de letra deseado en el panel Utilidades ¡Disfrútalo!

0

Si tiene un problema con la edición del texto atribuido en el inspector, copie y pegue el texto en un editor de texto enriquecido, ajústelo, cambie las opciones TextView Text a Atribuido y pegue. Vwala.

1

El siguiente código es para iOS 6.0 y superior. El resultado es que el texto "Esto está en negrita" estará en negrita y "Esto no está en negrita". será texto normal.

if ([self.registrationLabel respondsToSelector:@selector(setAttributedText:)]) 
{ 
    // iOS6 and above : Use NSAttributedStrings 
    const CGFloat fontSize = 17; 
    UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize]; 
    UIFont *regularFont = [UIFont systemFontOfSize:fontSize]; 
    //UIColor *foregroundColor = [UIColor clearColor]; 

    // Create the attributes 
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys: 
           boldFont, NSFontAttributeName, nil]; 
    NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys: 
           regularFont, NSFontAttributeName, nil]; 
    const NSRange range = NSMakeRange(0,12); // range of " 2012/10/14 ". Ideally this should not be hardcoded 

    // Create the attributed string (text + attributes) 
    NSString *text = @"This is bold and this is not bold.; 
    NSMutableAttributedString *attributedText = 
    [[NSMutableAttributedString alloc] initWithString:text 
              attributes:subAttrs]; 
    [attributedText setAttributes:attrs range:range]; 

    // Set it in our UILabel and we are done! 
    [self.registrationLabel setAttributedText:attributedText]; 
} 
Cuestiones relacionadas