![](/img/trans.png)
[英]Justify text in iOS (Swift or Objective-C) without breaking tracking/kerning/letter spacing
[英]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
但是,當應用程序運行時,它似乎並沒有在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.