How to make subscripts and superscripts using NSAttributedString?

前端 未结 5 1316
情书的邮戳
情书的邮戳 2020-11-27 15:40

I need to make subscripts for chemistry formulas (H2O, Na^2+, etc)?

Is this possible to do with NSAttributedString, or is there an alternative/easier way to make sub

5条回答
  •  天命终不由人
    2020-11-27 16:28

    On iOS, I had missed the kCTSuperscriptAttributeName constant but had good results with font size and "baseline". It gives you a little more control too for less obedient fonts:

    + (NSAttributedString *)attributedStringForText:(NSString *)normalText andSuperscript:(NSString *)superscriptText textSize:(CGFloat)textSize
    {
        UIFont *normalFont = [Styles mainFontWithSize:textSize];
        UIFont *superFont = [Styles mainFontWithSize:textSize / 2];
    
        NSMutableAttributedString *finalStr = [[NSMutableAttributedString alloc] initWithString:normalText attributes:@{NSFontAttributeName: normalFont}];
    
        NSAttributedString *superStr = [[NSAttributedString alloc] initWithString:superscriptText attributes:@{NSFontAttributeName: superFont, NSBaselineOffsetAttributeName:@(textSize/2)}];
    
        [finalStr appendAttributedString:superStr];
    
        return finalStr;
    }       
    

提交回复
热议问题