UITextView font is nil

L D picture L D · Oct 19, 2013 · Viewed 7.3k times · Source

I created a UITextView with a font size of 14 in a storyboard and hooked it up to the detailDescriptionLabel property of my ViewController. This code is in viewDidLoad:

self.detailDescriptionLabel.font=[UIFont systemFontOfSize:10];
NSLog(@"text is %@; font is %@", self.detailDescriptionLabel.text, self.detailDescriptionLabel.font);

The console output follows:

text is Lorem Ipsum; font is (null)

Why is the font set to nil? The setFont: is working; the font does shrink. I want to get the font so after a gesture I can call lineHeight on the font. This way, I can find out which line has been tapped with the following code:

int line = [tap locationInView:tap.view].y / self.detailDescriptionLabel.font.lineHeight;

Here, too, the font is nil. line is set to -2147483648, which is obviously not what I want.

Answer

Ty Cobb picture Ty Cobb · Oct 21, 2013

Try checking the "selectable" checkbox for this UITextView in Interface Builder. It's in the Attributes Inspector. Per @VahramDodoryan's comment below, you can then set selectable to false if you don't want to support selection.

I can't explain why this works, but it's probably a UIKit bug. I had an IBOutlet to a UITextView whose font property was nil, and it would not respond to any font or text-color changes in code until after its text property had been set. I arrived at this solution through trial-and-error.


If you're still encountering this issue on recent releases of iOS, consider opening a radar: