iOS:以编程方式设置UILabel的字体大小


83

我正在尝试设置UILabel的字体大小。无论我输入什么值,尽管文本大小似乎都没有变化。这是我正在使用的代码。

[self setTitleLabel:[[UILabel alloc] initWithFrame:CGRectMake(320.0,0.0,428.0,50.0)]];
[[self contentView] addSubview:[self titleLabel]];
UIColor *titlebg = [UIColor clearColor];
[[self titleLabel] setBackgroundColor:titlebg];
[[self titleLabel] setTextColor:[UIColor blackColor]];
[[self titleLabel] setFont:[UIFont fontWithName:@"System" size:36]];

Answers:


161

尝试[UIFont systemFontOfSize:36][UIFont fontWithName:@"HelveticaNeue" size:36][[self titleLabel] setFont:[UIFont systemFontOfSize:36]];


2
setFont在iOS 10.2中已弃用
TheJeff

76

目标C:

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

迅速:

label.font = label.font.fontWithSize(sizeYouWant)

只是更改UILabel的字体大小。


1
显然,setFont已过时,因此label.font = // Whatever font.
Rudolf Real

@FabricioPH我要如何设置label.font = // whatever currently system's font字体?
陈李咏

1
@ChenLiYong我不再从事iOS开发。也许Google搜索会显示有关设置或获取当前系统字体的一些相关结果。google.com/?#q=ios%20system%20font
鲁道夫·

22

Swift 3.0 / Swift 4.2 / Swift 5.0

labelName.font = labelName.font.withSize(15)

16

如果您正在寻找快速代码:

var titleLabel = UILabel()
titleLabel.font = UIFont(name: "HelveticaNeue-UltraLight",
                         size: 20.0)

6

这段代码非常适合我。

  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15,23, 350,22)];
  [label setFont:[UIFont systemFontOfSize:11]];

我也是[[self titleLabel] setFont:[UIFont systemFontOfSize:36]];没有,我也不知道为什么
Leon Leon

4

在Swift 3.0中,您可以在下面使用以下代码:

let textLabel = UILabel(frame: CGRect(x:containerView.frame.width/2 - 35, y: 
    containerView.frame.height/2 + 10, width: 70, height: 20))
    textLabel.text = "Add Text"
    textLabel.font = UIFont(name: "Helvetica", size: 15.0) // set fontName and Size
    textLabel.textAlignment = .center
    containerView.addSubview(textLabel) // containerView is a UIView


1

对于iOS 8

  static NSString *_myCustomFontName;

 + (NSString *)myCustomFontName:(NSString*)fontName
  {
 if ( !_myCustomFontName )
  {
   NSArray *arr = [UIFont fontNamesForFamilyName:fontName];
    // I know I only have one font in this family
    if ( [arr count] > 0 )
       _myCustomFontName = arr[0];
  }

 return _myCustomFontName;

 }

可能也是您的字体目标会员资格的问题。
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.