Reputation: 5268
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
Upvotes: 3
Views: 4941
Reputation: 17535
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:
Upvotes: 0
Reputation: 17535
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
Upvotes: 11
Reputation: 4277
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
Upvotes: 0
Reputation: 17851
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.
Upvotes: 2