Multiple colours in an NSString
or NSMutableStrings
are not possible. So I\'ve heard a little about the NSAttributedString which was introduced wit
I think, it is a very convenient way to use regular expressions
to find a range for applying attributes. This is how I did it:
NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:articleText];
NSRange range = [articleText rangeOfString:@"\\[.+?\\]" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:16] range:range];
[goodText addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range];
}
NSString *regEx = [NSString stringWithFormat:@"%@.+?\\s", [self.article.titleText substringToIndex:0]];
range = [articleText rangeOfString:regEx options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia-Bold" size:20] range:range];
[goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
}
[self.textView setAttributedText:goodText];
I was searching for a list of available attributes and didn't find them here and in a class reference's first page. So I decided to post here information on that.
Standard Attributes
Attributed strings support the following standard attributes for text. If the key is not in the dictionary, then use the default values described below.
NSString *NSFontAttributeName;
NSString *NSParagraphStyleAttributeName;
NSString *NSForegroundColorAttributeName;
NSString *NSUnderlineStyleAttributeName;
NSString *NSSuperscriptAttributeName;
NSString *NSBackgroundColorAttributeName;
NSString *NSAttachmentAttributeName;
NSString *NSLigatureAttributeName;
NSString *NSBaselineOffsetAttributeName;
NSString *NSKernAttributeName;
NSString *NSLinkAttributeName;
NSString *NSStrokeWidthAttributeName;
NSString *NSStrokeColorAttributeName;
NSString *NSUnderlineColorAttributeName;
NSString *NSStrikethroughStyleAttributeName;
NSString *NSStrikethroughColorAttributeName;
NSString *NSShadowAttributeName;
NSString *NSObliquenessAttributeName;
NSString *NSExpansionAttributeName;
NSString *NSCursorAttributeName;
NSString *NSToolTipAttributeName;
NSString *NSMarkedClauseSegmentAttributeName;
NSString *NSWritingDirectionAttributeName;
NSString *NSVerticalGlyphFormAttributeName;
NSString *NSTextAlternativesAttributeName;
NSAttributedString programming guide
A full class reference is here.
I always found working with attributed strings to be an incredibly long winded and tedious process.
So I made a Mac App that creates all the code for you.
https://itunes.apple.com/us/app/attributed-string-creator/id730928349?mt=12
Swift 4
let combination = NSMutableAttributedString()
var part1 = NSMutableAttributedString()
var part2 = NSMutableAttributedString()
var part3 = NSMutableAttributedString()
let attrRegular = [NSAttributedStringKey.font : UIFont(name: "Palatino-Roman", size: 15)]
let attrBold:Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15)]
let attrBoldWithColor: Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15),
NSAttributedStringKey.foregroundColor: UIColor.red]
if let regular = attrRegular as? [NSAttributedStringKey : NSObject]{
part1 = NSMutableAttributedString(string: "first", attributes: regular)
}
if let bold = attrRegular as? [NSAttributedStringKey : NSObject]{
part2 = NSMutableAttributedString(string: "second", attributes: bold)
}
if let boldWithColor = attrBoldWithColor as? [NSAttributedStringKey : NSObject]{
part3 = NSMutableAttributedString(string: "third", attributes: boldWithColor)
}
combination.append(part1)
combination.append(part2)
combination.append(part3)
Attributes list please see here NSAttributedStringKey on Apple Docs
- (void)changeColorWithString:(UILabel *)uilabel stringToReplace:(NSString *) stringToReplace uiColor:(UIColor *) uiColor{
NSMutableAttributedString *text =
[[NSMutableAttributedString alloc]
initWithAttributedString: uilabel.attributedText];
[text addAttribute: NSForegroundColorAttributeName value:uiColor range:[uilabel.text rangeOfString:stringToReplace]];
[uilabel setAttributedText: text];
}
This solution will work for any length
NSString *strFirst = @"Anylengthtext";
NSString *strSecond = @"Anylengthtext";
NSString *strThird = @"Anylengthtext";
NSString *strComplete = [NSString stringWithFormat:@"%@ %@ %@",strFirst,strSecond,strThird];
NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:strComplete];
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:[strComplete rangeOfString:strFirst]];
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor yellowColor]
range:[strComplete rangeOfString:strSecond]];
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor]
range:[strComplete rangeOfString:strThird]];
self.lblName.attributedText = attributedString;
Since iOS 7 you can use NSAttributedString
with HTML syntax:
NSURL *htmlString = [[NSBundle mainBundle] URLForResource: @"string" withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString
options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
documentAttributes:nil
error:nil];
textView.attributedText = stringWithHTMLAttributes;// you can use a label also
You have to add the file "string.html" to you project, and the content of the html can be like this:
<html>
<head>
<style type="text/css">
body {
font-size: 15px;
font-family: Avenir, Arial, sans-serif;
}
.red {
color: red;
}
.green {
color: green;
}
.blue {
color: blue;
}
</style>
</head>
<body>
<span class="red">first</span><span class="green">second</span><span class="blue">third</span>
</body>
</html>
Now, you can use NSAttributedString
as you want, even without HTML file, like for example:
//At the top of your .m file
#define RED_OCCURENCE -red_occurence-
#define GREEN_OCCURENCE -green_occurence-
#define BLUE_OCCURENCE -blue_occurence-
#define HTML_TEMPLATE @"<span style=\"color:red\">-red_occurence-</span><span style=\"color:green\">-green_occurence-</span><span style=\"color:blue\">-blue_occurence-</span></body></html>"
//Where you need to use your attributed string
NSString *string = [HTML_TEMPLATE stringByReplacingOccurrencesOfString:RED_OCCURENCE withString:@"first"] ;
string = [string stringByReplacingOccurrencesOfString:GREEN_OCCURENCE withString:@"second"];
string = [string stringByReplacingOccurrencesOfString:BLUE_OCCURENCE withString:@"third"];
NSData* cData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithData:cData
options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
documentAttributes:nil
error:nil];
textView.attributedText = stringWithHTMLAttributes;
Source