繁体   English   中英

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

[英]iOS/Objective-C UILabel text kerning

我一直在寻找如何增加UILabel的字符间距,以使我所使用的Apps的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 <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上生效,而且在Interface Builder中,文本也消失了。

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

提前致谢!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM