Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an italic UILabel without caring about the size?

I have a UILabel, whose text or attributedText properties I update programatically. Under some cases, I'd like to italicize it. I could either:

A) set the UILabel.font property:

myLabel.font = [UIFont italicSystemFontOfSize: 12.0];

B) or use an attributed string to do something similar:

myLabel.attributedText = [[NSAttributedString alloc] initWithString: @"my text" attributes: @{NSFontAttributeName: [UIFont italicSystemFontOfSize: 12.0]}]]

But I don't want to care about the size. I just want the "default" font AND size, but in italic. Currently, I'm actually using the obliqueness attribute:

NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
    initWithString: @"My Text"
    attributes: @{NSObliquenessAttributeName: @(0.5)}];
myLabel.attributedText = text;

This makes it so I don't have to care about whatever the size is, but I think obliqueness just approximates italics.

like image 874
Travis Griggs Avatar asked Feb 14 '23 06:02

Travis Griggs


2 Answers

You can make use of [UIFont systemFontSize].

myLabel.attributedText = [[NSAttributedString alloc] 
                     initWithString: @"my text" 
                         attributes: @{
              NSFontAttributeName: [UIFont italicSystemFontOfSize: 
                                         [UIFont systemFontSize]]}]];

Moreover, there are few more options to choose from:

+ (CGFloat)labelFontSize;//Returns the standard font size used for labels.
+ (CGFloat)buttonFontSize;//Returns the standard font size used for buttons.
+ (CGFloat)smallSystemFontSize;//Returns the size of the standard small system font.
+ (CGFloat)systemFontSize;//Returns the size of the standard system font.
like image 125
Raptor Avatar answered Feb 17 '23 03:02

Raptor


Another option is to read the point size directly off the labels font.

myLabel.font = [UIFont italicSystemFontOfSize:myLabel.font.pointSize];

myLabel.attributedText = [[NSAttributedString alloc] initWithString: @"my text" attributes: @{NSFontAttributeName: [UIFont italicSystemFontOfSize:myLabel.font.pointSize]}];
like image 23
Mick MacCallum Avatar answered Feb 17 '23 03:02

Mick MacCallum