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

时间:2016-06-15 05:22:03

标签: ios objective-c fonts interface-builder uilabel

我正在寻找如何在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中提供以下属性来调整字距,enter image description here

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

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

感谢高级!

1 个答案:

答案 0 :(得分:1)

您希望每次更新字距时都更新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