Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase the character spacing in UILabel

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.

like image 571
Dilip Avatar asked Dec 14 '13 07:12

Dilip


People also ask

How do you increase line spacing in UILabel?

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.

How do I add padding to UILabel Swift?

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.

What is UILabel?

A view that displays one or more lines of informational text.


2 Answers

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]; 
like image 74
B.S. Avatar answered Oct 01 '22 09:10

B.S.


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") 
like image 37
Steve Avatar answered Oct 01 '22 09:10

Steve