How to append the following characters ‡, †, * as superscript to NSString in iOS

元气小坏坏 提交于 2019-12-05 22:02:43

Try to use this one. And you need to #import <CoreText/CTStringAttributes.h>. This code works only in iOS6 or later version.

UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 200, 40)];
NSString *infoString=@"X2 and H20 A‡ B† C*";

NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];

[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(1, 1)];
[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@-1 range:NSMakeRange(8, 1)];
[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(12, 1)];
[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(15, 1)];
[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(18, 1)];

lbl.attributedText = attString;

[self.view addSubview:lbl];

Output

I hope this will help you

NSString does not allow you to format specific parts of the text. If you're planning to display your text in a UILabel, UITextField, or UITextView (and your app doesn't have to run on anything below iOS 6), you can use NSAttributedString and apply a kCTSuperscriptAttributeName attribute with the value @1. If you're using a UIWebView, use HTML's <sup> element.

This is how you could achieve that:

NSString *string = @"abcdefghi";

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];

NSInteger num1 = 1;
CFNumberRef num2 = CFNumberCreate(NULL, kCFNumberNSIntegerType, &num1);

[attrString addAttribute:(id)kCTSuperscriptAttributeName value:(id)CFBridgingRelease(num2) range:NSMakeRange(6, 3)];

self.label.attributedText = attrString;

, where label is a UILabel property already added to the UI.

Make sure you add first the CoreText framework, also add this line on top of you .m file.

Hope it helps you somehow

Swift

Step 1.

    import CoreText

Step 2.

    let range1 = NSMakeRange(1, 1)
    let range2 = NSMakeRange(5, 1)

    let mutableStr : NSMutableAttributedString = NSMutableAttributedString(string: "h20 x2")
    mutableStr.addAttribute(kCTSuperscriptAttributeName as String, value:-1, range: range1)
    mutableStr.addAttribute(kCTSuperscriptAttributeName as String, value:1, range: range2)

    self.lbl.attributedText = mutableStr

Output:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!