Reputation: 35
I am unable to apply both the attributes at the same. Either only color or subscript am able to apply. Here is my code
NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]initWithString:@"some text"];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Lato-Bold" size:16]
range:NSMakeRange(14,1)];
[attributedText addAttribute:(NSString *)kCTSuperscriptAttributeName value:@-1 range:NSMakeRange(14,1)];
[attributedText addAttribute:(NSString *)kCTForegroundColorAttributeName value:@{ NSForegroundColorAttributeName : [UIColor colorWithRed:85.0/255.0 green:38.0/255.0 blue:152.0/255.0 alpha:1.0] } range:(NSRange){0,6}];
Upvotes: 2
Views: 2679
Reputation: 1670
You can try with this code
[str addAttribute:(NSString *)kCTSuperscriptAttributeName value:@-1 range:NSMakeRange(14,1)];
[str setAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]}
range:(NSRange){0,7}];
Upvotes: 3
Reputation: 2999
Here is an update for your code workable.
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 100, 200, 44)];
[self.view addSubview:textView];
UIColor *color = [UIColor colorWithRed:85.0/255.0 green:38.0/255.0 blue:152.0/255.0 alpha:1.0];
UIFont *font = [UIFont fontWithName:@"Arial" size:20.0];
NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]initWithString:@"some text"];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Arial" size:16]//Lato-Bold, Your font name crahes
range:NSMakeRange(8,1)];//x(8) is start index,y(1) is length from start index x(8)
NSDictionary *attrs = @{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
[attributedText addAttributes:attrs range:NSMakeRange(0,6)];//start index start from 0, and length start counting from 1
//[attributedText addAttribute:(NSString *)kCTSuperscriptAttributeName value:@-1 range:NSMakeRange(14,1)];
textView.attributedText = attributedText;
OR
You can try with this.
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 100, 200, 44)];
NSString *newsTitle = @"Hello";
NSString *sportTtle = @"World";
NSString *title = [NSString stringWithFormat:@"%@ %@", newsTitle,sportTtle];
textView.text = title;
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont fontWithName:@"Arial" size:20.0];
NSDictionary *attrs = @{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
[attrStr addAttributes:attrs range:[textView.text rangeOfString:sportTtle]];
textView.attributedText = attrStr;
[self.view addSubview:textView];
Upvotes: 2