How to increase the character spacing in UILabel

2019-01-31 05:50发布

问题:

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.

回答1:

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];


回答2:

Swift extension for this

extension UILabel {
    func addCharactersSpacing(spacing:CGFloat, text:String) {
        let attributedString = NSMutableAttributedString(string: text)
        attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSMakeRange(0, text.characters.count))
        self.attributedText = attributedString
    }
}

So you can use it

MyLabel.addCharactersSpacing(5, text: "Some Text")


回答3:

Swift 4

extension UILabel {

   func setCharacterSpacing(characterSpacing: CGFloat = 0.0) {

        guard let labelText = text else { return }

        let attributedString: NSMutableAttributedString
        if let labelAttributedText = attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelAttributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // Character spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.kern, value: characterSpacing, range: NSMakeRange(0, attributedString.length))

        attributedText = attributedString
    }        

}

Swift 3

let label = UILabel()
let stringValue = "Sample text"
let attrString = NSMutableAttributedString(string: stringValue)
attrString.addAttribute(NSKernAttributeName, 2: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString


回答4:

   NSString *strDigit= @"001";
   NSString *strCrushImpact =[NSStringstringWithFormat:@"%d",[strDigit intValue]];

       // Set space in between character
   float spacing = 3.0f;

   NSMutableAttributedString *attributedStrDigit = [[NSMutableAttributedString alloc] initWithString:strWin];
   [strCrushImpact addAttribute:NSKernAttributeName value:@(spacing)
             range:NSMakeRange(0, [strDigit length])];
 label.attributedText = attributedStrDigit;