2009-03-04 8 views

Respuesta

13

Aquí está un ejemplo específico basado en las respuestas dadas por danielpunkass y Peter Hosey:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:12], NSFontAttributeName, nil]; 
NSAttributedString *text = [[NSAttributedString alloc] initWithString:@"Hello" attributes: attributes]; 
NSSize textSize = [text size]; 

Para los nuevos en Objective-C/Cocoa, como yo, un ejemplo realmente va un largo camino. Si vienes de C++/Java/C# o lo que sea que la sintaxis de Objective-C pueda parecer realmente extraña y dado que Apple no incluye mucho código de muestra en su documentación de Cocoa, aprender esto es algo difícil.

+2

+ [dictionaryWithObjectsAndKeys NSDictionary:]: segundo objeto de cada par debe ser no nula. O, ¿se olvidó de cancelar su lista de parámetros? – Ziggy

6

Una forma es sizeWithAttributes:, como dijo danielpunkass. La otra forma es crear un NSAttributedString y preguntarlo por su size. La única diferencia es que una forma te da un objeto con el texto y los atributos juntos (la cadena atribuida), mientras que la otra los mantiene separados.

7

El siguiente código es similar a lo que yo uso para un CALayer texto multiplataforma:

#if defined(TARGET_IPHONE_SIMULATOR) || defined(TARGET_OS_IPHONE) 
    UIFont *theFont = [UIFont fontWithName:fontName size:fontSize]; 
    CGSize textSize = [text sizeWithFont:theFont]; 
#else 
    NSFont *theFont = [NSFont fontWithName:fontName size:fontSize]; 
    CGSize textSize = NSSizeToCGSize([text sizeWithAttributes:[NSDictionary dictionaryWithObject:theFont forKey: NSFontAttributeName]]); 
#endif 

Esto le da una CGSize para un texto llamado NSString, con un nombre de fuente de fontName y el tamaño de fontSize.

0

Si utiliza un presentador, p. UILabel/NSLabel (en lugar de pedirle a la cuerda que dibuje). Entonces deberías pedirle a este objeto el tamaño correcto.

Ver Mike Weller's blog about labels para un análisis detallado.

+2

No hay NSLabel. La contraparte de Cacao de UILabel es NSTextField (con 'border 'y' editable' desactivados). –

0

Ohh bajo iOS6 se puede obtener el tamaño correcto de esta manera:

CGSize textSize = [theString sizeWithFont:theFont 
          forWidth:160.0f 
         lineBreakMode:NSLineBreakByWordWrapping]; 
Cuestiones relacionadas