2011-08-22 15 views
14

Tengo un problema que en iOS estoy usando UILabel para mostrar texto de 2,3 líneas, quiero alinear el texto como justificado, pero no encuentro ninguna opción para hacerlo. ¿Alguna sugerencia de cómo justificar el texto en la etiqueta?Justificar texto en UILabel iOS

i poner estas líneas para hacer iniciarlo desde la parte superior

CGSize maximumSize = CGSizeMake(300, 9999); 
NSString *textString = someString; 
UIFont *textFont = [UIFont fontWithName:@"Futura" size:14]; 
CGSize textStringSize = [textString sizeWithFont:textFont 
           constrainedToSize:maximumSize 
            lineBreakMode:text.lineBreakMode]; 

CGRect textFrame = CGRectMake(10, 110, 300, textStringSize.height); 
text.frame = textFrame; 

por lo que cualquier truco como esto para hacerle justfiy Gracias

Respuesta

31

Ahora existe una forma conveniente de justificar el texto desde iOS6. Se puede crear una instancia de NSAttributedString, establecer las propiedades adecuadas y asignar esta cadena atribuido a un texto que representa la vista como UILabel, UITextView, etc. Es tan fácil como esto:

  1. crear una instancia de NSMutableParagraphStyle y establecer sus propiedades .

    NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init]; 
    paragraphStyles.alignment = NSTextAlignmentJustified;  //justified text 
    paragraphStyles.firstLineHeadIndent = 10.0;    //must have a value to make it work 
    
  2. Cree NSDictionary para atributos de texto y cree cadenas atribuidas.

    NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyles}; 
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: string attributes: attributes]; 
    
  3. Establecer cadena atribuida a una etiqueta.

    existingLabel.attributedText = attributedString; 
    
+1

"paragraphStyles.firstLineHeadIndent = 10.0" eso era lo que estoy buscando. ¡Gracias! – Neru

+0

¡Funciona como un encanto! ¡Gracias! –

4

no puede hacerse Me temo - no así con UILabel .

Puede utilizar el UIWebView o una biblioteca de tercera parte, como OHAttributedLabel

feliz :) Codificación

Actualización:

Esta respuesta ha sido ya obsoleta iOS6. Por favor refiérase a la respuesta de Tankista.

+3

esta solución es ahora obsoleto, echa un vistazo a mi respuesta a continuación –

0

Se puede hacer fácilmente, pero debe usar Core Text.

subclase un UIView, añadir una propiedad NSString, crear una NSAttributedString y pasar kCTJustifiedTextAlignment valor de la clave kCTParagraphStyleSpecifierAlignment, tire del NSAttributedString utilizando cuarzo o CoreText en su método drawRect.

edición: kCTParagraphStyleSpecifierAlignment clave para el valor kCTJustifiedTextAlignment se debe utilizar para crear una estructura CTParagraphStyleRef y pasa como un valor para kCTParagraphStyleAttributeName clave a la hora de crear el NSAttributedString.

0

Según lo mencionado por @martin, mi clase OHAttributedLabel puede hacer esto muy fácilmente. (Lo encontrará en mi github y también encontrará muchas referencias en SO también)

+1

Usted tiene todo lo necesario para que en el archivo de cabecera, no hay problema para hacer todo eso. Hay un '' 'UITextAlignmentJustify''' #define (que es igual a' '' kCTJustifiedTextAlignment''') que puede usar para aplicar alineación de texto en su NSAttributedString (usando '' 'setTextAlignment: lineBreakMode:' '' método de NSAttributedString + Attributes .h).Y si no desea que se pueda hacer clic en los enlaces, también hay una propiedad @ para eso: '' 'automaticallyAddLinksForType = 0''' no agregará ningún enlace ni a las URL, ni a los teléfonos, ni a nada. – AliSoftware

+0

Desde iOS6, es mejor usar 'UILabel' nativo con' NSAttributedString'. –

+0

@ Cœur Totalmente de acuerdo (es por eso que 'OHAttributedLabel' está en desuso desde hace algún tiempo, por cierto). Para aquellos interesados, extraje todas las prácticas categorías 'NSAttributedString' en mi nuevo pod [OHAttributedStringAdditions] (https://github.com/AliSoftware/OHAttributedStringAdditions) ahora, lo que ayuda a manipular objetos' NS (Mutable) AttributedString' más fácilmente (y es compatible con iOS6 + y TextKit). – AliSoftware

Cuestiones relacionadas