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

后端 未结 5 1741
無奈伤痛
無奈伤痛 2021-02-13 18:33

There are a myriad of settings for NSAttributedParagraphStyle that I can see in Interface Builder:

5条回答
  •  既然无缘
    2021-02-13 19:00

    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 attributedText?.length == nil { return }
    
                let attrStr = NSMutableAttributedString(attributedString: attributedText!)
                let range = NSMakeRange(0, attributedText!.length)
                attrStr.addAttributes([NSAttributedStringKey.kern: kerning], range: range)
                attributedText = attrStr
            }
        }
    }
    

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

    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

提交回复
热议问题