iphone xcode uilabel spacing uifont

iphone - ¿Cómo cambiar el espacio entre letras de UILabel/UIFont?



xcode spacing (5)

Ya busqué cargas y no pude encontrar una respuesta.

Tengo un UILabel normal, definido de esta manera:

UILabel *totalColors = [[[UILabel alloc] initWithFrame:CGRectMake(5, 7, 120, 69)] autorelease]; totalColors.text = [NSString stringWithFormat:@"%d", total]; totalColors.font = [UIFont fontWithName:@"Arial-BoldMT" size:60]; totalColors.textColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0]; totalColors.backgroundColor = [UIColor clearColor]; [self addSubview:totalColors];

Y quería que el espaciado horizontal entre las letras fuese más ajustado, mientras mantuve el tamaño de la fuente.

¿Hay alguna forma de hacer esto? Debería ser algo bastante básico de hacer.

Saludos chicos, Andre

ACTUALIZAR:

Entonces me forzaron a hacerlo así:

- (void) drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSelectFont (context, "Arial-BoldMT", 60, kCGEncodingMacRoman); CGContextSetCharacterSpacing (context, -10); CGContextSetTextDrawingMode (context, kCGTextFill); CGContextSetRGBFillColor(context, 221/255.0, 221/255.0, 221/255.0, 221/255.0); CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0); CGContextSetTextMatrix(context, xform); char* result = malloc(17); sprintf(result, "%d", totalNumber); CGContextShowTextAtPoint (context, 0, 54, result, strlen(result)); }

Pero necesito alinear esto a la derecha. Podría hacerlo manualmente si supiera el ancho del texto dibujado, pero resulta casi imposible encontrarlo.

He leído sobre ATSU, pero no pude encontrar ningún ejemplo.

Esto apesta: /


Desde iOS 6 puedes usar NSAttributedString en UILabel.

En la cadena atribuida puede usar el atributo NSKernAttributeName para establecer el espaciado entre letras

NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString: @"Test test test test "]; [attrStr addAttribute:NSKernAttributeName value:@(4.0) range:NSMakeRange(0, attrStr.length)]; UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 300, 300, 100)]; label.attributedText = attrStr;


En Swift:

let myTitle = "my title" let titleLabel = UILabel() let attributes: NSDictionary = [ NSFontAttributeName:UIFont(name: "HelveticaNeue-Light", size: 20), NSForegroundColorAttributeName:UIColor.whiteColor(), NSKernAttributeName:CGFloat(2.0) ] let attributedTitle = NSAttributedString(string: myTitle, attributes: attributes as? [String : AnyObject]) titleLabel.attributedText = attributedTitle titleLabel.sizeToFit()


He encontrado una solución para el espaciado entre letras y la alineación a la derecha.

Aquí va:

NSString *number = [NSString stringWithFormat:@"%d", total]; int lastPos = 85; NSUInteger i; for (i = number.length; i > 0; i--) { NSRange range = {i-1,1}; NSString *n = [number substringWithRange:range]; UILabel *digit = [[[UILabel alloc] initWithFrame:CGRectMake(5, 10, 35, 50)] autorelease]; digit.text = n; digit.font = [UIFont fontWithName:@"Arial-BoldMT" size:60]; digit.textColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0]; digit.backgroundColor = [UIColor clearColor]; [self addSubview:digit]; CGSize textSize = [[digit text] sizeWithFont:[digit font]]; CGFloat textWidth = textSize.width; CGRect rect = digit.frame; rect.origin.x = lastPos - textWidth; digit.frame = rect; lastPos = rect.origin.x + 10; }

El espacio entre letras es el "10" en la última línea. La alineación viene de los últimosPos.

Espero que esto ayude a cualquiera por ahí.


He extendido UILabel para cambiar el espaciado entre caracteres. Esto debería resolver la caja y extraer la fuente, el texto, el color, etc. de la propia UILabel (¡la codificación adecuada!).

Puede notar que dibujo el texto dos veces, primero con un color claro. Esto es para centrar automáticamente el texto en la etiqueta. Si bien esto puede ser ineficiente, ¿no es bueno ser centrado automáticamente?

¡Disfrutar!

@interface RALabel : UILabel { } @end @implementation RALabel - (void) drawRect:(CGRect)rect { // Drawing code CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman); CGContextSetCharacterSpacing(context, 1); CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]); CGAffineTransform myTextTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f ); CGContextSetTextMatrix (context, myTextTransform); // draw 1 but invisbly to get the string length. CGPoint p =CGContextGetTextPosition(context); float centeredY = (self.font.pointSize + (self.frame.size.height- self.font.pointSize)/2)-2; CGContextShowTextAtPoint(context, 0, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]); CGPoint v =CGContextGetTextPosition(context); // calculate width and draw second one. float width = v.x - p.x; float centeredX =(self.frame.size.width- width)/2; CGContextSetFillColorWithColor(context, [self.textColor CGColor]); CGContextShowTextAtPoint(context, centeredX, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]); }


No en ninguna versión disponible públicamente de iPhone OS. ;-) Si usted es un desarrollador de iPhone actual, puede hacerse una idea de dónde va el sistema operativo de iPhone mirando las notas "Novedades" para iPhone OS 3.2.

Actualización: iOS v3.2, que agregó soporte para kerning, aún estaba bajo NDA cuando publiqué esto. Para obtener una respuesta actualizada a la fecha, consulte Cómo configurar el kerning en el iPhone UILabel .