Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make characters equal width in UILabel

Tags:

ios

uilabel

I have a problem when using UILabel.

enter image description here

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~

like image 843
CoderJason1992 Avatar asked Dec 06 '22 17:12

CoderJason1992


2 Answers

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
like image 56
Warpling Avatar answered Jan 04 '23 12:01

Warpling


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 fraction 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.

like image 25
vikingosegundo Avatar answered Jan 04 '23 12:01

vikingosegundo