使用 Objective C 中的分数创建字体描述符

Creating Font Descriptors with Fractions in Objective C

我在 Objective C 中显示分数时遇到问题,尽管等效代码在 Swift 中有效。我一定是遗漏了一些非常明显的东西??

Swift代码:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    //: Playground - noun: a place where people can play

    let pointSize = self.label.font.pointSize

    let systemFontDesc = UIFont.systemFont(ofSize: pointSize, weight: UIFontWeightLight).fontDescriptor

    let fractionFontDesc = systemFontDesc.addingAttributes(
        [
            UIFontDescriptorFeatureSettingsAttribute: [
                [
                    UIFontFeatureTypeIdentifierKey: kFractionsType,
                    UIFontFeatureSelectorIdentifierKey: kDiagonalFractionsSelector,
                    ], ]
        ] )

    print(fractionFontDesc)
    self.label.font = UIFont(descriptor: fractionFontDesc, size:pointSize)

    print("label.font.descriptor: \(self.label.font.fontDescriptor)")
}

结果:

Objective C

中的等效代码
-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    CGFloat pointSize = _label.font.pointSize;

    UIFontDescriptor *systemFontDesc = [UIFont systemFontOfSize:pointSize weight:UIFontWeightLight].fontDescriptor;

    UIFontDescriptor *fractionDescriptor = [systemFontDesc fontDescriptorByAddingAttributes:@{ UIFontDescriptorFeatureSettingsAttribute : @{
                                                                                                       UIFontFeatureTypeIdentifierKey: @(11), // kFractionsType
                                                                                                       UIFontFeatureSelectorIdentifierKey: @(2)}}]; // kDiagonalFractionsSelector

    NSLog(@"%@\n\n", fractionDescriptor);

    UIFont *fracFont = [UIFont fontWithDescriptor:fractionDescriptor size:pointSize];

    NSLog(@"fracFont.fontDescriptor: %@\n\n", fracFont.fontDescriptor);

    [_label setFont: fracFont];

    NSLog(@"label.font.descriptor: %@\n\n", _label.font.fontDescriptor);
}

结果:

问题是表达式

fontDescriptorByAddingAttributes:@{
   UIFontDescriptorFeatureSettingsAttribute : @{

最后一个 @{ 表示您的 UIFontDescriptorFeatureSettingsAttribute 是一个字典。那是错的。它需要是 array 字典。 (仔细看看你原来的Swift代码,你会发现是这样的。)

在我看来,最好是在一行中形成字典,在另一行中创建一个数组,然后在第三行中调用 fontDescriptorByAddingAttributes。这样你就会清楚自己在做什么。现在你只是把自己和所有那些嵌套的文字搞混了......