How to change an UILabel/UIFont's letter spacing?

末鹿安然 提交于 2019-11-27 11:19:58

From iOS 6 you can use NSAttributedString in UILabel.

In attributed string you can use attribute NSKernAttributeName to set letter spacing

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;

I've extended UILabel to change the character spacing. This should work out the box and pulls font, text, color etc from the UILabel itself (proper coding!).

You may notice I draw the text twice, first with clear color. This is to auto center the text in the label. Whilst this may be inefficient - isn't it nice to be auto centered?

Enjoy!

@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]);

}

I've come up with a solution for the letter spacing and the alignment to the right.

Here it goes:

    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;
    }

The letter spacing is the "10" on the last line. The alignment comes from the lastPos.

Hope this helps anyone out there.

In 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()
Zack

Not in any publicly available version of iPhone OS. ;-) If you are a current iPhone Developer, you can get an idea of where iPhone OS is going by looking through the "What's New" notes for iPhone OS 3.2.

Update: iOS v3.2, which added support for kerning, was still under NDA when I posted this. For an update-to-date answer, see How to set kerning in iPhone UILabel.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!