I am creating an app in >=iOS6. And I want to change the character spacing in UILabel. I have added the custom font "FUTURABT HEAVY" in my app but the Character are too close to eachother.
I have find the good code here to increase the character spacing. But if i tried to change it than my text became left- align in stead of center.
Please help me with this situation.
To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels." This is a really old answer, and other have already addded the new and better way to handle this.. Please see the up to date answers provided below.
If you have created an UILabel programmatically, replace the UILabel class with the PaddingLabel and add the padding: // Init Label let label = PaddingLabel() label. backgroundColor = . black label.
A view that displays one or more lines of informational text.
You should probably use NSAttributedString
with NSKernAttributeName
attribute
Here is a small example:
UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds]; NSString *string = @"Some important text"; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string]; float spacing = 5.0f; [attributedString addAttribute:NSKernAttributeName value:@(spacing) range:NSMakeRange(0, [string length])]; label.attributedText = attributedString; [self.view addSubview:label];
Swift extension for this
extension UILabel { func addCharactersSpacing(spacing:CGFloat, text:String) { let attributedString = NSMutableAttributedString(string: text) attributedString.addAttribute(NSAttributedString.Key.kern, value: spacing, range: NSMakeRange(0, text.count-1)) self.attributedText = attributedString } }
So you can use it
MyLabel.addCharactersSpacing(5, text: "Some Text")
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