4

我尝试使用给定字体系列名称来获得粗体 iOS UIFont 的方法似乎仅适用于某些字体。例如:

UIFont* font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:12];
NSLog(@"A: Font name: %@", [font fontName]);

// desired method works for Helvetica Neue
UIFontDescriptor *desc = [[UIFontDescriptor alloc] init];
desc = [desc fontDescriptorWithFamily:@"Helvetica Neue"];
desc = [desc fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold];
font = [UIFont fontWithDescriptor:desc size:12];
NSLog(@"B: Font name: %@", [font fontName]);

// desired method fails for Times New Roman
desc = [[UIFontDescriptor alloc] init];
desc = [desc fontDescriptorWithFamily:@"Times New Roman"];
NSLog(@"desc: %@", desc);
desc = [desc fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold];
NSLog(@"desc bold: %@", desc);

打印(在 iOS 8.1 模拟器上):

A: Font name: TimesNewRomanPS-BoldMT
B: Font name: HelveticaNeue-Bold
desc: UICTFontDescriptor <0x7f9be0d05e80> = { NSFontFamilyAttribute = "Times New Roman"; }
desc bold: (null)

这是一个错误,还是它不适合每个字体系列(实际上有一个粗体变体)?我真的不想被迫解析字体名称以寻找“粗体”或类似的东西。

4

2 回答 2

4

这是一个错误。fontDescriptorWithSymbolicTraits:保证返回一个字体描述符;因此,返回nil是意外行为。

事实上,如果你用 Swift 重写同样的东西,它会导致崩溃,因为desc它不是可选的:

var desc = UIFontDescriptor()
desc = desc.fontDescriptorWithFamily("Times New Roman")
desc = desc.fontDescriptorWithSymbolicTraits(.TraitBold)
println(desc); //crash

是否UIFontDescriptor会返回 aUIFont是一个单独的问题。你应该归档一个雷达。

于 2014-10-29T04:56:11.797 回答
1

@neural5torm 为这个 iOS8 错误提供了一个很好的解决方法:

NSString *fontFamily = @"Arial";
BOOL isBold = YES;
BOOL isItalic = YES;
CGFloat fontSize = 20.0;
UIFontDescriptor *fontDescriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:
    @{
        @"NSFontFamilyAttribute" : fontFamily,
        @"NSFontFaceAttribute" : (isBold && isItalic ? @"Bold Italic" : (isBold ? @"Bold" : (isItalic ? @"Italic" : @"Regular")))
    }];
UIFont *font = [UIFont fontWithDescriptor:fontDescriptor size:fontSize];

原帖: https ://stackoverflow.com/a/26222986/3160700

于 2015-01-02T19:37:07.977 回答