在iOS 13上带有子/上标的NSAttributedString

时间:2019-12-21 17:10:39

标签: ios objective-c nsattributedstring

我维护着一个用Objective-C编写的应用程序,在某些地方它显示了化学式。为实现子标和上标,我在NSString扩展名中添加了这段代码。

- (NSMutableAttributedString *) chemicalFormulaWithFont: (UIFont *) font
{
    if (self.length == 0)
        return nil;

    NSDictionary *normalAttribute = @{NSFontAttributeName: font};
    NSDictionary *baselineAttribute = @{NSBaselineOffsetAttributeName : @0};

    UIFont *smallFont = [UIFont fontWithName: font.fontName
                                        size: font.pointSize * 0.75];

    NSString *superscriptAttributeName = (NSString *)kCTSuperscriptAttributeName;

    NSDictionary *subscriptAttribute = @{superscriptAttributeName : @-1,
                                         NSFontAttributeName: smallFont};

    NSDictionary *superscriptAttribute = @{superscriptAttributeName : @1,
                                           NSFontAttributeName: smallFont};

    NSCharacterSet *decimalDigits = [NSCharacterSet decimalDigitCharacterSet];

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: self];

    NSUInteger length = attributedString.length;
    NSRange range = NSMakeRange(0, length);
    [attributedString addAttributes: normalAttribute range: range];

    while (range.location != NSNotFound)
    {
        range = [attributedString.string rangeOfCharacterFromSet: decimalDigits options: 0 range: range];

        if (range.location != NSNotFound)
        {
            unichar ch = [attributedString.string characterAtIndex: range.location - 1];

            if ((ch != '-') && (ch != '+'))
            {
                [attributedString addAttributes: subscriptAttribute range: range];
            }

            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
        }
    }

    range = NSMakeRange(0, length);

    // if last two characters are +, - , 2+, 3+, 2-, etc then add superscript

    unichar ch = [attributedString.string characterAtIndex: length - 1];

    if ((ch == '-') || (ch == '+'))
    {
        range = NSMakeRange(length - 1, 1);

        ch = [attributedString.string characterAtIndex: length - 2];

        if (ch >= '0' && ch <='9')
            range = NSMakeRange(length - 2, 2);
        [attributedString addAttributes: superscriptAttribute range: range];
    }

    [attributedString addAttributes: baselineAttribute range: range];

    return attributedString;
}

字体是“ Avenir-Medium”

这在iOS 12上运行良好,但在iOS 13上,我不再看到子标题和上标。

问题是,我的Mac机太旧而无法运行Xcode 11-我停留在10.2版上。因此,即使在连接了iPhone(运行iOS 13)的情况下,我也无法针对iOS> 12.1进行调试。

我能想到的一件事是Avenir-Medium在iOS 13上不再支持此功能,但似乎不太可能。

关于NSAttributedString,iOS 13中可能有其他更改吗?

0 个答案:

没有答案