iOS / Objective-C UILabel文本字距调整

我正在寻找如何增加UILabel的字符间距,以使我的UI设计实现更具吸引力。 我找到了以下答案,它告诉它允许调整Text Kerning ,并且它是用Swift编写的。

但我需要的是Objective-C解决方案。 所以我尝试转换以下代码片段:

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

以下是Objective-C:
KerningLabel.h:

 #import  IB_DESIGNABLE @interface KerningLabel : UILabel @property (nonatomic) IBInspectable CGFloat kerning; @end 

KerningLabel.m:

 #import "KerningLabel.h" @implementation KerningLabel @synthesize kerning; - (void) setAttributedText:(NSAttributedString *)attributedText { if ([self.attributedText length] > 0) { NSMutableAttributedString *muAttrString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText]; [muAttrString addAttribute:NSKernAttributeName value:@(self.kerning) range:NSMakeRange(0, [self.attributedText length])]; self.attributedText = muAttrString; } } @end 

它在XCode IB中给出以下属性来调整字距, 在此处输入图像描述

但是,当应用程序运行时,它似乎并没有在UI上生效,而且在界面生成器中,文本也会消失。

请有人帮助我,并指出我做错了什么。

先谢谢了!

您希望每次更新字距时更新您的attributedText 。 所以,你的.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