How can I get the font size and font name of a UILabel?
Asked Answered
Y

4

111

I have a UILabel which I set a font size and a font name with Interface Builder. Now I have to read the values of both in my ViewController.

How can I do this?

Yalu answered 1/2, 2011 at 17:53 Comment(1)
This method has been deprecated iOS7, take a look at this article #19129297Chloral
S
265

Add a property to your view controller's .h file:

@property (nonatomic, retain) IBOutlet UILabel *label;

Link the label to this IBOutlet under "File's Owner" outlets in Interface Builder. If not using ARC, make sure you release it in -dealloc

- (void)dealloc
{
    [self.label release];
    [super dealloc];
}

Then to get the font name and size all you need is

NSString *fontName = self.label.font.fontName;
CGFloat fontSize = self.label.font.pointSize;
Safranine answered 1/2, 2011 at 19:4 Comment(4)
Does not work. I can write text in it, but the fontName and pointSize is null.Yalu
Do you mean that you can programmatically change the text of the label, but you can't access the fontName and pointSize? I edited the above answer to include self.label, instead of just label, since I didn't mention creating an instance variable for label.Safranine
Also, make sure you've hooked up the label in Interface Builder with the IBOutlet you made in File's Owner (the view controller).Safranine
Ah, I forgot the connection in IB with the File's Owner.Yalu
O
37

Swift:

var currentFontSize = button.titleLabel?.font.pointSize
Orgel answered 5/12, 2014 at 11:17 Comment(1)
They could have named it font.size whats up with pointSize. When you are creating font you use size UIFont(name: ..., size: ...)Tranquil
C
16

Pointsize value is not the Font Size of used in UIFont size property. Say if you go set interface builder font size to 14 and do a print of the pointSize you'll get only 11.

Catamaran answered 23/6, 2011 at 16:26 Comment(1)
Seems to be working now. If i set the font size of a label in the interface builder / storyboard editor to 17... myLabel.font.pointSize returns 17.Provisional
W
2

you have to attach it to a UILabel IBOutlet, and then, label.font...

Whippletree answered 1/2, 2011 at 17:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.