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~
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With