How to create an NSarray with NSAttributedStrings but keeping the attributes within the array? - objective-c

I want to store different strings with different attributes and store all of them in one array and then display the objects in one label but each object with its respective attribute.
Any suggestions?
EDIT: Solution derived from rmaddy's answer
NSDictionary *redAttrs = #{NSForegroundColorAttributeName:[UIColor redColor]};
NSDictionary *greenAttrs = #{NSForegroundColorAttributeName:[UIColor colorWithRed:0.118 green:0.506 blue:0.000 alpha:1.000]};
NSDictionary *orangeAttrs = #{NSForegroundColorAttributeName:[UIColor orangeColor]};
NSString *stringUm = #"Brazil";
NSString *stringDois = #"USA";
NSString *stringTres = #"England";
NSMutableAttributedString *redString = [[NSMutableAttributedString alloc] initWithString:stringUm];
[redString setAttributes:redAttrs range:NSMakeRange(0,4)];
NSMutableAttributedString *greenString = [[NSMutableAttributedString alloc] initWithString:stringDois];
[greenString setAttributes:greenAttrs range:NSMakeRange(0,2)];
NSMutableAttributedString *orangeString = [[NSMutableAttributedString alloc] initWithString:stringTres];
[orangeString setAttributes:orangeAttrs range:NSMakeRange(0,4)];
NSArray *myStrings = [[NSArray alloc] initWithObjects:redString, greenString, orangeString, nil];
NSLog(#"%#", [myStrings description]);
NSMutableAttributedString *result = [[NSMutableAttributedString alloc]init];
NSAttributedString *delimiter = [[NSAttributedString alloc] initWithString: #", "];
for (NSAttributedString *str in myStrings) {
if (result.length) {
[result appendAttributedString:delimiter];
}
[result appendAttributedString:str];
}
_lblUm.attributedText = result;

Your question is very unclear. But based on your comment to gerrytan's answer, your goal is clearer.
If you have an array of NSAttributedString objects, then you can create a single string by appending them all together with an NSMutableAttributedString.
NSArray *myStrings = ... // your array of NSAttributedString objects
NSMutableAttributedString *result = [[NSMutableAttributedString alloc] init];
// Put this delimiter between each string - change as desired
NSAttributedString *delimiter = [[NSAttributedString alloc] initWithString:#", "];
for (NSAttributeString *str in myStrings) {
if (result.length) {
[result appendAttributedString:delimiter];
}
[result appendAttributedString:str];
}
myLabel.attributedText = result;

UILabel only supports one NSAttributedString. I think what you can do is to place multiple UILabel side by side for each string on the array

Related

changing colour of a part of string objective c [duplicate]

This question already has answers here:
Are there any analogues of [NSString stringWithFormat:] for NSAttributedString
(4 answers)
Closed 6 years ago.
I have a string like this
NSString * string = [[NSString alloc]initwithformat: #"The current balance left is %# out of %#",leftAmount,totalAmount];
How can i change the colour of string recieved as %# without knowing the range of the recieved string.
Do something like this,
NSString *leftAmount = #"1000";
NSString *totalAmount = #"2000";
UIColor *color = [UIColor redColor];
NSDictionary *attrs = #{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:leftAmount attributes:attrs];
NSAttributedString *attrStr1 = [[NSAttributedString alloc] initWithString:totalAmount attributes:attrs];
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:#"The current balance left is "];
[string appendAttributedString:attrStr];
NSMutableAttributedString * string1 = [[NSMutableAttributedString alloc] initWithString:#" out of "];
[string1 appendAttributedString:attrStr1];
[string appendAttributedString:string1];
NSLog(#"Your Full String - %#", string);
Hope this will help you.
do something like this,
NSString *leftAmount,*totalAmount;
leftAmount = #"1000";
totalAmount = #"2000";
NSString * string = [NSString stringWithFormat:#"The current balance left is %# out of %#",leftAmount,totalAmount];
NSDictionary *attribs = #{
NSForegroundColorAttributeName: [UIColor blueColor],
NSFontAttributeName: [UIFont systemFontOfSize:12]
};
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:string
attributes:attribs];
UIColor *grayColor = [UIColor colorWithRed:186.0f/255.0f green:186.0f/255.0f blue:186.0f/255.0f alpha:1];
NSRange leftAmountTextRange = [string rangeOfString:leftAmount];
[attributedText setAttributes:#{NSForegroundColorAttributeName:grayColor}
range:leftAmountTextRange];
It'll also calculate the dynamic data value range.
I hope it will helps you,
Thanks.

How can I word wrap with NSMutableAttributedString?

NSArray *myArray = #[#"1st:array1",
#"2nd:array2",
#"3rd:array3"
];
NSString *labelString = [myArray componentsJoinedByString:#"\n"];
In this codelabelStringcan be word wrapped.
But if use NSMutableAttributedString like this
NSAttributedString *resultString = [resultArray componentsJoinedByString:#"\n"];
it can't be joined by #"\n". Any other method is existed? Thanks.
It's not difficult. You just know one thing.
AttributedString can't have \n maybe. So you just put \n in NSString.
And just make NSAttributedString from this NSString.
Here this code. I hope this code help your work.
NSString *commentString;
NSMutableArray *resultArray = [[NSMutableArray alloc]initWithCapacity:50];
for (InstagramComment *comment in comments) {
commentString = [NSString stringWithFormat:#"%#:%#\n", comment.user.username, comment.text];
NSMutableAttributedString *styledCommentString = [[NSMutableAttributedString alloc]initWithString:commentString];
[resultArray addObject:styledCommentString];
}
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc]init];
for (int i = 0; i < resultArray.count; ++i) {
[resultString appendAttributedString:[resultArray objectAtIndex:i]];
} [cell.comment setAttributedText:resultString];

How to combine 2 strings into one nsatributed string?

NSString * strTimeBefore = [timeBefore componentsJoinedByString:#" "];
NSString * strTimeAfter = [timeAfter componentsJoinedByString:#" "];
I want the resulting string to be an NSAttributedString where the time in strTimeAfter is in bold
You probably want something like:
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = [NSString stringWithFormat:#"%# %#", strTimeBefore, strTimeAfter;
// start at the end of strTimeBefore and go the length of strTimeAfter
NSRange boldedRange = NSMakeRange([strTimeBefore length] + 1, [strTimeAfter length]);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
And my answer is cribbed from Jacob's answer to this very closely related question.
Take two attribute string in that store your first string into one attribute string without changing its attributes, In second attribute string store your second string with changing its attibutes and then append both attribute string into one NSMutableAttributeString Try like this below:-
NSString * strTimeBefore = [timeBefore componentsJoinedByString:#" "];
NSString * strTimeAfter = [timeAfter componentsJoinedByString:#" "];
NSAttributedString *attrBeforeStr=[[NSAttributedString alloc]initWithString:strTimeBefore];
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:[NSColor yellowColor] forKey:NSBackgroundColorAttributeName];
NSFont *font = [[NSFontManager sharedFontManager] fontWithFamily:#"Arial" traits:NSBoldFontMask weight:5 size:14];
[attributes setObject:font forKey:NSFontAttributeName];
NSAttributedString *attrAftStr=[[NSAttributedString alloc]initWithString:strTimeAfter attributes:];
NSMutableAttributedString *string=[[NSMutableAttributedString alloc] init];
[string appendAttributedString:attrBeforeStr];
[string appendAttributedString:strTimeAfter];
Note: You can change font color as well in attribute string, if it is required.

Encoding issue: An NSString into a key of an NSDictionary

So I'm taking a data file and encoding it into a string:
///////////////////////////////
// Get the string
NSString* dataString = [[NSString alloc] initWithData:data
encoding:encoding];
NSLog(#"dataString = %#",dataString);
The file was a list of French words and they NSLog fine, showing appropriate accents (just one example):
abandonnèrent
Now, in the very next part of the code I take this NSString of the file contents and convert it to a dictionary where the words are the keys and the objects are two additional dictionaries:
///////////////////////////////
// Now parse the file (string)
NSMutableDictionary *mutableWordlist = [[NSMutableDictionary alloc] init];
int i = 0;
for (NSString *line in [dataString componentsSeparatedByString:#"\n"]) {
NSArray *words = [line componentsSeparatedByString:#"\t"];
NSNumber *count = [NSNumber numberWithInt:(i+1)];
NSArray *keyArray;
NSArray *objectArray;
if ([words count] < 2) { // No native word
keyArray = [[NSArray alloc] initWithObjects:#"frequency", nil];
objectArray = [[NSArray alloc] initWithObjects:count, nil];
}
else {
keyArray = [[NSArray alloc] initWithObjects:#"frequency", #"native", nil];
objectArray = [[NSArray alloc] initWithObjects:count, [words[1] lowercaseString], nil];
}
NSDictionary *detailsDict = [[NSDictionary alloc] initWithObjects:objectArray forKeys:keyArray];
[mutableWordlist setObject:detailsDict forKey:[words[0] lowercaseString]];
i++;
}
self.wordlist = mutableWordlist;
NSLog(#"self.wordlist = %#", self.wordlist);
But here the keys have encoding issues and log as so if they have an accent:
"abandonn\U00e8rent
" = {
frequency = 24220;
};
What is happening?
Nothing (wrong) is happening.
When you NSLog an NSString it is being output as Unicode text. However when you NSLog the NSDictionary they keys are being output with unicode escape sequences, \U00e8 is the escape code you can use in a string if you cannot type an è - say because your source file is in ASCII.
So the difference is only in how the string is being printed, the string is not different.
HTH

Unable to add custom links to OHAttributeLabel

I am using OHAttributeLabel to add custom links to my label's text. The code that I am using is pasted below. It used to work with the older version of OHAttributed label (2010), however with the new version (recently updated), the text in my label are no longer clickable as links.
Can anyone advise what I am missing here?
// Set Question Label
Question *question = self._answerForCell.question;
NSString *questionText = [NSString stringWithFormat:#"Q: %#", question.text];
CustomOHAttributLabel *thisQuestionLabel = (CustomOHAttributLabel *)[self.contentView viewWithTag:QUESTIONLABEL_TAG];
//Set up dictionary for question
NSString *questionStr = [question.text stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *urlForQn = [NSString stringWithFormat:#"dailythingsfm://redirect_to/questions/%#/answers?text=%#&nickname=%#&question_id=%#&question_curious=%i&showEveryOneTab=%i", question.slug, questionStr, [[UserInfo sharedUserInfo] getNickname], question.qid, question.curious, 1];
NSString *qnStartIndex = #"0";
NSString *qnLength = [NSString stringWithFormat:#"%i", [questionText length]];
NSDictionary *qnDict = [NSDictionary dictionaryWithObjectsAndKeys:qnStartIndex, #"start", qnLength, #"length", urlForQn, #"url", nil];
NSArray *array = [NSArray arrayWithObject:qnDict];
[thisQuestionLabel setLabelwithText:questionText fontSize:QUESTION_FONT_SIZE andSubStringToURLArrayViaRange:array withHexColor:#"#555555"];
//Method to set the text in UILabel to a custom link
- (void)setLabelwithText:(NSString *)text fontSize:(CGFloat)fontSize andSubStringToURLArrayViaRange:(NSArray *)array withHexColor:(NSString *)textColor
{
NSMutableAttributedString *attrStr = [NSMutableAttributedString attributedStringWithString:text];
[attrStr setFont:[UIFont systemFontOfSize:fontSize]];
[attrStr setTextColor:[UIColor grayColor]];
[self removeAllCustomLinks];
for (NSDictionary *dict in array) {
NSString *start = [dict objectForKey:#"start"];
NSString *length = [dict objectForKey:#"length"];
NSString *url = [dict objectForKey:#"url"];
NSUInteger startIndex = [start intValue];
NSUInteger len = [length intValue];
NSRange range = NSMakeRange(startIndex, len);
[attrStr setFont:[UIFont boldSystemFontOfSize:fontSize] range:range];
[attrStr setTextColor:[UIColor colorWithHexString:textColor] range:range];
[self addCustomLink:[NSURL URLWithString:url] inRange:range];
}
self.attributedText = attrStr;
}
I have to use 'setLink' method instead of addCustomLink for the latest OHAttribute Library (3.2.1)