简体   繁体   中英

IOS Objective C UILabel font size is keeping its storyboard setting

I am using objectiveC for an old project and I am setting the label font size programmatically like this :

UIFont *font = [self fontToFitHeight:NSLocalizedString(@"#61_NEW_FINAL", nil) font:self.rulesLabel.font size:self.rulesLabel.frame.size.height];
[self.rulesLabel setFont:font];
NSLog(@"after call : fontszie is : %lf",self.rulesLabel.font.pointSize);

I can include the helper function if needed, but it returns me what I want, which is a font with fontsize around 5, which i see printed.

But when running that my font size is definitely not 5, but instead whatever value I have in the Storyboard settings (in my case 16). Above code is called inside viewDidLoad .

What am I missing?

NSAttributedString can include one or more fonts, perhaps this is your issue. If you have set the text of the label to be an attributed string that contains a font or a color, changing the base font or color of the label will not make a difference. In order for it to work as expected, you can either remove any font formatting of your attributed string (that I assume that you set through IB) or recreate the string in code and add the proper font to it, like so:

 NSString *text = NSLocalizedString(@"#61_NEW_FINAL", @"Don't leave this out");
 UIFont *font = [self fontToFitHeight:text font:self.rulesLabel.font size:self.rulesLabel.frame.size.height];
 NSMutableAttributedString *labelAttributes = [[NSMutableAttributedString alloc] initWithString:text];

 [labelAttributes addAttribute:NSFontAttributeName
                               value:font
                               range:NSMakeRange(0, labelAttributes.length)];

At this point, changing the font of the label will make absolutely no difference to its apperance, since the entire text has a predefined font already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM