我正在搜索如何增加UILabel
中的字符间距,以使我的UI设计实现更具吸引力。我发现了下面的answer, which tells it allows to adjust the 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 <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中给出了以下属性来调整字距:
但当应用程序运行时,它似乎并没有在UI上生效,而且在界面生成器中,文本也消失了。
我做错了什么?
1条答案
按热度按时间4ngedf3f1#
您希望在每次更新字距调整时更新
attributedText
。所以,你的.h应该看起来像:你的.m: