How to set kerning in iPhone UILabel

后端 未结 9 1164
Happy的楠姐
Happy的楠姐 2020-11-30 01:12

I am developing an iPhone app, and I want to set kerning in UILabel. The code I\'ve written (possibly around kCTKernAttributeName) seems to be in error. How mig

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 02:05

    Taking DBD's answer, I made a category on UILabel which allows setting the kerning if running on iOS6+ with graceful fall back to just setting text on previous iOS versions. Might be of help to others...

    UILabel+TextKerning.h

    #import 
    
    @interface UILabel (TextKerning)
    
    /**
     * Set the label's text to the given string, using the given kerning value if able.
     * (i.e., if running on iOS 6.0+). The kerning value specifies the number of points
     * by which to adjust spacing between characters (positive values increase spacing,
     * negative values decrease spacing, a value of 0 is default)
     **/
    - (void) setText:(NSString *)text withKerning:(CGFloat)kerning;
    
    /**
     * Set the kerning value of the currently-set text.  The kerning value specifies the number of points
     * by which to adjust spacing between characters (positive values increase spacing,
     * negative values decrease spacing, a value of 0 is default)
     **/
    - (void) setKerning:(CGFloat)kerning;
    
    @end
    

    UILabel+TextKerning.m

    #import "UILabel+TextKerning.h"
    
    @implementation UILabel (TextKerning)
    
    -(void) setText:(NSString *)text withKerning:(CGFloat)kerning
    {
        if ([self respondsToSelector:@selector(setAttributedText:)])
        {
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
            [attributedString addAttribute:NSKernAttributeName
                                     value:[NSNumber numberWithFloat:kerning]
                                     range:NSMakeRange(0, [text length])];
            [self setAttributedText:attributedString];
        }
        else
            [self setText:text];
    }
    
    -(void) setKerning:(CGFloat)kerning
    {
        [self setText:self.text withKerning:kerning];
    }
    

提交回复
热议问题