UILabel 字体大小对于粗体字体不正确

UILabel font size is not correct for bold fonts

我正在动态创建 UIlabels,第一个标签我使用 Bold 样式。

for (int i = 0; i < vehicles.count; ++i) {
    CGRect labelRect = CGRectMake(i * (self.frame.size.width / vehicles.count),
                                  3, self.frame.size.width / vehicles.count,
                                  13);
    UILabel *label = [[UILabel alloc] initWithFrame:labelRect];
    label.textColor = thumbColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.text = vehicles[i].vehicleClass;
    UIFont *labelFont;
    if (i == 0) {
        labelFont = [UIFont fontWithName:@"Avenir Next-Bold" size:9.0];
    } else {
        labelFont = [UIFont fontWithName:@"Avenir Next" size:9.0];
    }
    label.font = labelFont;

    [vehiclesLabels addObject:label];
    [self addSubview:label];
}

但是画成这样

为什么第一个标签更大?

对于 "Avenir Next" 系列字体,您必须使用这些名称:

AvenirNext-MediumItalic, AvenirNext-大胆, AvenirNext-超轻, AvenirNext-DemiBold, AvenirNext-HeavyItalic, AvenirNext-重型, AvenirNext-Medium, AvenirNext-Italic, AvenirNext-UltraLightItalic, AvenirNext-BoldItalic, AvenirNext-常规, AvenirNext-DemiBoldItalic

将 Avenir Next-Bold 更改为 AvenirNext-Bold,将 Avenir Next 更改为 AvenirNext-Regular

只需要更改下面这行代码即可。

labelFont = [UIFont fontWithName:@"AvenirNextCondensed-Bold" size:9.0];

对于所有字体家族名称检查,请使用以下代码。

NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
    NSArray *fontNames;
    NSInteger indFamily, indFont;
    for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
    {
        NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
        fontNames = [[NSArray alloc] initWithArray:
                     [UIFont fontNamesForFamilyName:
                      [familyNames objectAtIndex:indFamily]]];
        for (indFont=0; indFont<[fontNames count]; ++indFont)
        {
            NSLog(@"    Font name: %@", [fontNames objectAtIndex:indFont]);
        }

    }

从适合您的字体名称中删除空格

UIFont *labelFont;
    if (i == 0) {
        labelFont = [UIFont fontWithName:@"AvenirNext-Bold" size:9.0];
    } else {
        labelFont = [UIFont fontWithName:@"AvenirNext-Regular" size:9.0];
    }
    label.font = labelFont;

在您当前的代码中,字体未应用于该数组中的第一个字符串。如果您尝试打印 labelfont 的日志,则 i=0 时它将为 nil。 如果您打印 label.font 的日志,您可以看到以下输出

(lldb) po label.font
<UICTFont: 0x7fbbb36185a0> font-family: ".SFUIText-Regular"; font-weight: normal; font-style: normal; font-size: 17.00pt

要使粗体字体正常工作,请尝试以下操作,

labelFont = [UIFont fontWithName:@"AvenirNext-Bold" size:9.0];

希望这会有所帮助。