I am developing an iPhone app, and I want to set kerning in UILabel. The code I've written (possibly around kCTKernAttributeName
) seems to be in error. How might I approach fixing this?
NSMutableAttributedString *attStr;
NSString *str = @"aaaaaaa";
CFStringRef kern = kCTKernAttributeName;
NSNumber *num = [NSNumber numberWithFloat: 2.0f];
NSDictionary *attributesDict = [NSDictionary dictionaryWithObject:num
forKey:(NSString*)kern];
[attStr initWithString:str attributes:attributesDict];
CGRect frame1 = CGRectMake(0, 0, 100, 40);
UILabel *label1 = [[UILabel alloc] initWithFrame:frame1];
label1.text = attStr
[self.view addSubview:label1];
As far as I am aware,
UILabel
will not render the characteristics ofNSAttributedString
. There are a couple of nice open source solutions. I recently used TTTAttributedLabel as a swap in replacement for UILabel that accepts NSAttributedString.DTCoreText (former NSAttributedString+HTML) is also getting a bit of buzz lately.
In Swift 2.0...
Add an extension:
Now, just set your UILabel as attributedText:
Obviously, I added a bunch of parameters that you may not need. Play around -- feel free to rewrite the method -- I was looking for this on a bunch of different answers so figured I'd post the whole extension in case it helps someone out there... -rab
Before:
After:
Here's a Swift 2 extension that let's you set a UILabel's kerning via code or storyboard:
Demo usage:
or
The demo uses 3.0 kerning for drama, but I've found 0.1 - 0.8 tends to work well in practice.
Old question, but you can do it now (easily).
For Nov 2013, Just to expand on this great answer, here's some totally typical code. Usually you'd set the font as well. Note in the comments the old-fashioned way using ordinary old .text. Hope it helps someone
Just to be up-to-date here, iOS 6 introduced attributedText for
UILabel
andUITextView
!UILabel reference:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/attributedText
Just do this in Swift: