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

时间:2017-02-16 15:43:27

标签: objective-c uilabel uifont uifontdescriptor

我在Objective C中显示分数时遇到问题,即使等效代码在Swift中有效。我一定错过了很明显的东西吗?

Swift Code:

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)")
}

结果:

swift result

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);
}

结果:

objective c output

1 个答案:

答案 0 :(得分:3)

问题在于表达式

fontDescriptorByAddingAttributes:@{
   UIFontDescriptorFeatureSettingsAttribute : @{

最后@{表示您的UIFontDescriptorFeatureSettingsAttribute是字典。那是错的。它必须是字典的数组。 (仔细看看你原来的Swift代码,你会发现是这样的。)

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