UILabel:如何设置字体大小?

42

如何从 UILabel 中设置字体大小?

我的代码:

UILabel *myView = [[UILabel alloc] initWithFrame:RectFrame];
[myView setBackgroundColor:[UIColor blueColor]];
[myView setText:[NSString stringWithFormat:@" A"]];
[myView setFont:[12] ]; <--- Error
[self.view addSubview:myView];
7个回答

120
[myView setFont:[UIFont systemFontOfSize:12]];
或者
[myView setFont:[UIFont boldSystemFontOfSize:12]];
或者针对字体族进行设置
[myView setFont:[UIFont fontWithName:@"Helvetica" size:12]];

8
如果您的UILabel字体是在IB storyboard中定义的,而您只想增加字号大小,那么这样做是可行的,对我有效;)

[_label setFont: [_label.font fontWithSize: sizeYouWant]];

或者

[self.label setFont: [self.label.font fontWithSize: sizeYouWant]];

其他人提到的另一种方法也行:

[_label setFont:[UIFont systemFontOfSize:13.0]];

6

查看UIFont类。之后,您可能会明白为什么应该这样使用它:

[myView setFont:[UIFont systemFontOfSize:12]];

4

请记住用户可以全局设置他们想要的文本大小,因此您不应该使用固定的字体大小,如“12”。请使用以下字体:

[UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]

[UIFont preferredFontForTextStyle:UIFontTextStyleBody]
[UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline]
[UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]
[UIFont preferredFontForTextStyle:UIFontTextStyleCaption1]
[UIFont preferredFontForTextStyle:UIFontTextStyleCaption2]

我认为UILabel的默认字体是Caption1,其他字体会更大或更小。如果用户在设备上选择大字体或小字体,它们将自适应。 (如果用户选择非常小的字体大小,则字体大小12实际上可能比普通标签大小更大)。


3
UILabel *myView = [[UILabel alloc] initWithFrame:RectFrame];

[myView setBackgroundColor:[UIColor blueColor]];

[myView setText:[NSString stringWithFormat:@" A"]];

[myView setFont:[UIFont systemFontOfSize:12]];

[self.view addSubview:myView];

你能加上一些解释吗? - Philipp M

3

Swift 4及以上版本。

你也可以尝试使用它。

label.font = UIFont.systemFont(ofSize: 10) 

2

在Swift中

yourLabel.font = UIFont(name:"name of font-family you want", size: 9)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接