How do I create a bold UIFont from a regular UIFont?

后端 未结 7 1900
醉话见心
醉话见心 2020-12-08 19:08

If I have a UIFont object, is it possible to convert it to bold? I don\'t know the font name, I just have a UIFont object. What I want is a function like

<
7条回答
  •  無奈伤痛
    2020-12-08 19:50

    iOS 7 introduces a new UIFontDescriptor class, which makes it a lot easier:

    UIFont *font = [UIFont fontWithName:@"Helvetica Neue" size:12];
    NSLog(@"plain font: %@", font.fontName); // “HelveticaNeue”
    
    UIFont *boldFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold] size:font.pointSize];
    NSLog(@"bold version: %@", boldFont.fontName); // “HelveticaNeue-Bold”
    
    UIFont *italicFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic] size:font.pointSize];
    NSLog(@"italic version: %@", italicFont.fontName); // “HelveticaNeue-Italic”
    
    UIFont *boldItalicFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic] size:font.pointSize];
    NSLog(@"bold & italic version: %@", boldItalicFont.fontName); // “HelveticaNeue-BoldItalic”
    

    For people who got here looking for a Cocoa (macOS) equivalent, UIFontDescriptor comes from NSFontDescriptor, available since 10.3.

提交回复
热议问题