brandonscript brandonscript - 5 months ago 27
iOS Question

How do you adjust text kerning using Interface Builder in Xcode 7?

There are a myriad of settings for

NSAttributedParagraphStyle
that I can see in Interface Builder:




But none of these are for text kerning. Is there a way to adjust the text kerning in Xcode 7's Interface Builder for attributed text?

(Please don't answer with how to do this in code - I already know how to do that!)

Answer

Create a subclass of UILabel call it KerningLabel have it be comprised of the following code:

import UIKit
@IBDesignable
class KerningLabel: UILabel {

    @IBInspectable var kerning:CGFloat = 0.0{
        didSet{
            if ((self.attributedText?.length) != nil)
            {
                let attribString = NSMutableAttributedString(attributedString: self.attributedText!)
                attribString.addAttributes([NSKernAttributeName:kerning], range:NSMakeRange(0, self.attributedText!.length))
                self.attributedText = attribString
            }
        }
    }


}

Drag out a label. Change it to your UILabel subclass. Adjust the kerning as desired. enter image description here

In obj-c:

.h

IB_DESIGNABLE
@interface KerningLabel : UILabel

@property (nonatomic) IBInspectable CGFloat kerning;

@end

.m

@implementation KerningLabel

- (void)setKerning:(CGFloat)kerning
{
    _kerning = kerning;
    if(self.attributedText)
    {
        NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
        [attribString addAttribute:NSKernAttributeName value:@(kerning) range:NSMakeRange(0, self.attributedText.length)];
        self.attributedText = attribString;
    }
}

@end

Comments