如何在 UILabel 中使字符等宽

how to make characters equal width in UILabel

我在使用 UILabel 时遇到问题。

我这里有两个label(上图),字体等宽,textAlignment都是左边的,都是10个字符,但是每个字符的宽度不同,所以不能一一对齐,我正在尝试动态添加间距,但我没有这样做,那么我该如何解决呢?非常感谢~

您可以使用 NSAttributedString 像这样调整字母间距。

在Objective-C中:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"111111111"];
[attributedString addAttribute:NSKernAttributeName
                         value:@(4)
                         range:NSMakeRange(0, 9)];

self.label.attributedText = attributedString;

在Swift中:

let attributedString = NSMutableAttributedString(string: "000000000")
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.5), range: NSRange(location: 0, length: 9))

label.attributedText = attributedString

对于 Specific,您可以更改 1 set 4 和其他 1.5 的 NSKernAttributeName 的值。

OutPut 会像:

失败的原因是您使用的是比例字体,意思是:字符将占据单独的宽度。 i 只占 m.

的一小部分

使用等宽字体,所有字符将具有相同的宽度。

label.font = UIFont(name:"Courier", size: 17)

出于同样的原因,代码编辑器中使用了 Courier 和其他等宽字体。

如果您的目标是 iOS 7+!

,则无需使用等宽字体

来自UseYourLoaf blog

let bodyFontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.body)
let bodyMonospacedNumbersFontDescriptor = bodyFontDescriptor.addingAttributes(
    [
        UIFontDescriptorFeatureSettingsAttribute: [
            [
                UIFontFeatureTypeIdentifierKey: kNumberSpacingType,
                UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector
            ]
        ]
    ])

let bodyMonospacedNumbersFont = UIFont(descriptor: bodyMonospacedNumbersFontDescriptor, size: 16.0)

myLabel.font = bodyMonospacedNumbersFont

这是SF字体造成的。如果你更喜欢使用系统字体,我们可以使用 monospacedSystemFont / monospacedDigitSystemFont:

// Number & Alphabet
UIFont.monospacedSystemFont(ofSize: 24, weight: .medium)

// Number only
UIFont.monospacedDigitSystemFont(ofSize: 24, weight: .medium)