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

yhqotfr8  于 2023-06-25  发布在  iOS
关注(0)|答案(1)|浏览(122)

我正在搜索如何增加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上生效,而且在界面生成器中,文本也消失了。
我做错了什么?

4ngedf3f

4ngedf3f1#

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

相关问题