如何使用NSAttributedString制作下标和上标?

Mah*_*hir 25 objective-c nsstring nsattributedstring

我需要为化学公式(H2O,Na ^ 2 +等)做下标吗?

这可能与NSAttributedString有关,还是有替代/更简单的方式来制作下标?

Rob*_*ann 33

这是我在iOS 6中所做的.首先添加CoreText和QuartzCore框架.然后导入:

#import <QuartzCore/QuartzCore.h>
#import <CoreText/CTStringAttributes.h>
#import <CoreText/CoreText.h>
Run Code Online (Sandbox Code Playgroud)

我做了一个小函数,它输入一个普通的NSString并导出一个NSMutableAttributedString,其中包含上标中的最后一个字符.这可以修改为允许设置上标或下标,将kCTSuperscriptAttributeName值更改为-1.您还可以添加一个变量来指定将上标放在字符串中的位置.现在它只是假设字符串的结尾.

- (NSMutableAttributedString *)plainStringToAttributedUnits:(NSString *)string;
{
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
    UIFont *font = [UIFont systemFontOfSize:10.0f];
    UIFont *smallFont = [UIFont systemFontOfSize:9.0f];

    [attString beginEditing];
    [attString addAttribute:NSFontAttributeName value:(font) range:NSMakeRange(0, string.length - 2)];
    [attString addAttribute:NSFontAttributeName value:(smallFont) range:NSMakeRange(string.length - 1, 1)];
    [attString addAttribute:(NSString*)kCTSuperscriptAttributeName value:@"1" range:NSMakeRange(string.length - 1, 1)];
    [attString addAttribute:(NSString*)kCTForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.length - 1)];
    [attString endEditing];
    return attString;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我想使用它时,我可以执行以下操作将其放在UITextField中:

    NSString *qlwUnitsPlainText = @"m3";
    self.quantityLoadWeightUnits_textField.attributedText = [self plainStringToAttributedUnits:qlwUnitsPlainText];
Run Code Online (Sandbox Code Playgroud)

我希望这有助于其他人,那里没有很多例子!

  • 你不应该认为NSMakeRange参数是firstPosition和length(而不是firstPosition和lastPosition).在示例中,读者可能会误导. (3认同)

Mar*_*ams 28

这可以做到NSAttributedString.您正在寻找的属性常量取决于您的平台.对于Mac OS X来说,它就是NSSuperscriptAttributeName在iOS上kCTSuperscriptAttributeName.传递下标的负值.

唯一需要注意的是,UILabel在iOS上无法绘制NSAttributedStrings(但是,iOS 6的手指交叉).您需要使用Core Text绘制文本或找到一些UILabel可以绘制的第三方替换NSAttributedString.


Har*_*ngh 9

在iOS上,我错过了kCTSuperscriptAttributeName常量,但在字体大小和"基线"方面有很好的结果.对于不那么顺从的字体,它也为你提供了更多的控制:

+ (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;
}       
Run Code Online (Sandbox Code Playgroud)