iOS / Objecitve-C UILabel文字字距

我正在寻找如何增加UILabel的字符间距,使我的UIdevise实现更具吸引力。 我发现下面的答案,它告诉它允许调整文本string ,它是用Swift编写的。

但是我需要的是一个Objective-C解决scheme。 所以我试图转换下面的代码片段:

 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 <UIKit/UIKit.h> 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中给出以下属性来调整Kerning, 在这里输入图像说明

但是,当应用程序正在运行时,它似乎不会在用户界面上生效,而且在界面生成器中文本消失。

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

先谢谢了!

每次更新字距时,都要更新您的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