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

后端 未结 5 1371
小蘑菇
小蘑菇 2020-12-02 12:32

I\'ve searched loads already and couldn\'t find an answer.

I have a normal UILabel, defined this way:

    UILabel *totalColors = [[[UILabel alloc] in         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 12:59

    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.

提交回复
热议问题