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

怎甘沉沦 提交于 2019-12-10 10:07:07

问题


I need append the following characters ‡, †, * as superscript to NSString in iOS . Need your help. I use the following http://en.wikipedia.org/wiki/General_Punctuation_(Unicode_block) link but they are appending to NSString , But i want them as superscript


回答1:


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




回答2:


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.




回答3:


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




回答4:


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:



来源:https://stackoverflow.com/questions/16707747/how-to-append-the-following-characters-as-superscript-to-nsstring-in-ios

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