如何在UILabel中使字符宽度相等
使用UILabel
时遇到问题。
我这里有两个标签(上面的图片),它们有相同的字体和相等的宽度,textAlignment都是左边的,它们都有10个字符,但是每个字符都有不同的宽度所以它不能一个接一个地对齐,我正在尝试动态添加间距,但我没有这样做,所以我该如何解决? 非常感谢〜
它失败的原因是你使用的是比例字体,这意味着:字符会占用一个单独的宽度。 i
只需要摩擦m
。
使用等宽字体,而不是所有字符都具有相同的宽度。
label.font = UIFont(name:"Courier", size: 17)
出于同样的原因,在代码编辑器中使用Courier和其他等宽字体。
如果您的目标是iOS 7+,则无需使用等宽字体!
来自UseYourLoaf博客 :
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
您可以使用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会像: