how to make characters equal width in UILabel

怎甘沉沦 提交于 2019-12-07 08:55:23

问题


I have a problem when using UILabel.

I have two labels here(above images), they have equal font and equal width, textAlignment are both left, they both have 10 characters, but each character have different width so it can't be aligned one by one, I‘m trying to add spacing dynamically but I failed to do that, so how can I fix it? thanks a lot~


回答1:


The reason it fails is you are using a proportional font, meaning: characters will take up an individual width. An i will just take a friction of a m.

Use a monospaced font, than all characters will have the same width.

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

for the same reason Courier and other monospaced fonts are used in code editors.




回答2:


No need to use a monospace font if you're targetting iOS 7+!

From the 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



回答3:


You can adjust letter spacing like this, using NSAttributedString.

In Objective-C:

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

self.label.attributedText = attributedString;

In Swift:

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

label.attributedText = attributedString

For Specific you can change value of NSKernAttributeName for 1 set 4 and for other 1.5.

OutPut will be Like :



来源:https://stackoverflow.com/questions/38560422/how-to-make-characters-equal-width-in-uilabel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!