NSTextView making bold text using an array - objective-c

I have an array which has the following structure:
(
[0] = (
[0] = #"Title string"
[1] = #"Some content string"
)
[1] = (
[0] = #"Title string"
[1] = #"Some content string"
)
[2] = (
[0] = #"Title string"
[1] = #"Some content string"
)
...
)
and so on and so fourth to a variating amount of reoccurrence.
My goal is to try and merge it all into one single string to display in an NSTextField, and make every title string bold. So the code above would look something like this if it were outputted.
Title String
Some content string
Title String
Some content string
Title String
Some content string
My first question is how could make a single string where certain text is bold; and my second question is how could I take that string and send it to the NSTextField?
So far this is what I've done.I've tried using NSMutableAttributedString to make the string like so:
NSMutableAttributedString *contentString = [NSMutableAttributedString alloc];
for (int i=0; i<[result count]; i++) {
[contentString addAttribute:NSFontAttributeName
value:[NSFont fontWithName:#"HelveticaNeue-Bold" size:16.0]
range:NSRangeFromString(result[i][0])];
}
But I couldn't figure out how to append anything else to the string, or try and print just that alone because I got this error when trying to the following to display it in the NSTextField.
[self->contentView setString:contentString];
Incompatible pointer types sending 'NSMutableAttributedString *' to paramater of type 'NSString *'
So I tried this instead, but got a different error
[self->contentView attributedString:contentString];
No visible #interface for 'NSTextView' declares the selector 'attributedString'

Managed to find a way to make it work
NSMutableAttributedString *contentString = [NSMutableAttributedString alloc];
for (int i=0; i<[result count]; i++) {
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#\n%#\n\n", result[i][0], result[i][1]]];
NSDictionary *attributes = #{
NSFontAttributeName : [NSFont fontWithName:#"HelveticaNeue-Bold" size:12.0]
};
NSString *subtitle = [NSString stringWithFormat:#"%#", result[i][0]];
[resultString setAttributes:attributes range:NSMakeRange(0, [subtitle length])];
[contentString appendAttributedString:resultString];
}
[self->content setString:#""];
[[self->content textStorage] appendAttributedString:contentString];
The solution lies within the last line of code. All that needed to be done was instead of passing data to setString, use textStorage instead and pass an object to it. (I think I got the terminology right)
Bue yeah hope this helps anyone in the future!

How's this...
NSMutableAttributedString *contentString = [[NSMutableAttributedString alloc] init];
for (int i = 0; i < [result count]; i++) {
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#\n%#\n\n", result[i][0], result[i][1]]];
[resultString addAttribute:NSFontAttributeName
value:[NSFont fontWithName:#"HelveticaNeue-Bold" size:16.0]
range:NSRangeFromString(result[i][0])];
[contentString appendAttributedString:resultString];
}
Some notes about your other code. Make sure to match your [NSMutableAttributedString alloc] with an init like [[NSMutableAttributedString alloc] init]
You should realize that NSMutableAttributedString is not a subclass of NSString, but instead of NSObject, so setString: is not a method available to you.
NSTextView uses insertText: to set it's value.

Related

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 view the entire content of an array in a label (xcode 4.1)

i'm programming in Obj-c with xcode4.1, i have an array with numbers in it, and i want to visualize all of them in a label...can anyone help me around this please?
thanks!
this is the code:
combinedString=[[NSMutableArray alloc] init];
NSString *finalStringLabel=#"";
for (i=0; i<=textLength; i++) {
//character coding
char myChar = [myString characterAtIndex:i];
NSString *myCharS=[NSString stringWithFormat:#"%c", myChar];
int asciiCode=[myCharS characterAtIndex:0];
NSString *asciiS=[NSString stringWithFormat:#"%i", asciiCode];
[combinedString addObject:asciiS];
}
finalStringLabel=[NSString stringWithFormat:#"", [combinedString componentsJoinedByString:#"."]];
myLabel.text=finalStringLabel;
[combinedString release];
}
You can use this
NSArray *yourArray;
NSString *createdString = [yourArray componentsJoinedByString:#" "];
myLabel.text = createdString;
As your array is combinedString,
combinedString=[[NSMutableArray alloc] init];
looks like you are providing values after this line or this is not a property (this is a local as you are releasing it later), and your code in not complete.
Anyways,
You don't need to create an empty string and then assign new object to it, need to do as :
myLabel.text=[combinedString componentsJoinedByString:#"."];
[combinedString release];
}

Convert NSString to HTML and set HTML text into UILabel [duplicate]

This question already has answers here:
How to create a UILabel or UITextView with bold and normal text in it?
(5 answers)
Closed 9 years ago.
Is it possible to convert a NSString to html and set as a label?
The code below shows the NSString I want to set finalPrice as bold text and finalStr&shipping string as normal text
NSString *myText = [NSString
stringWithFormat:
#"%#\nFinal price including $%.2f Shipping and all discount: <b>$%.2f</b>",
finalStr,shipping,finalPrice];
lbl.text = myText;
I want to set multiple color and multiple text type into same dyanamic label.
use following label for bold effects. Or you can get code from that class.
DAAttributedStringUtils
and also see this
Different Label
Edit
NSString *myText = [NSString stringWithFormat:#"%#\nFinal price including $%.2f Shipping and all discount: %%B$%.2f%%b",finalStr,shipping,finalPrice];
DAAttributedLabel* lbl = [[DAAttributedLabel alloc] initWithFrame:CGRectMake(30.0f, 30.0f, 260.0f, 24.0f)];
lbl.backgroundColor = [UIColor colorWithRed:0.9f green:0.9f blue:1.0f alpha:1.0f];
lbl.text = (id)[formatter formatString:myText];
[self.view addSubview:lbl];
Try using NSAttributedString
There are already several questions around this here like
How do you use NSAttributedString?
NSString * textString = #"Hello Bold";
NSInteger _stringLength = [textString length];
NSMutableAttributedString * attString = [[NSMutableAttributedString alloc] initWithString:textString];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica" size:14.0f]; range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica-Bold" size:14.0f]; range:NSMakeRange(6, 4)];
myLabel.attributedText = attString;
(code not tested)
Edit:
label.attributedText is only available for iOS 6.0+
FYI, the answer above suggesting the use of DAAttributedStringUtils and DAAttributedLabel didn't mention that these are convenience classes for the use of NSAttributedString. They make formatting NSAttributedString instances a little easier. As an example, here's how to do the same formatting described about by HAS using DAAttributedStringUtils:
float finalPrice = 34.99, shipping = 4.99;
// Setup the formatter
DAAttributedStringFormatter* formatter = [[DAAttributedStringFormatter alloc] init];
formatter.defaultFontFamily = #"Georgia";
formatter.defaultFontSize = 12.0f;
formatter.colors = #[ [UIColor blackColor], [UIColor redColor] ];
NSAttributedString* attrStr = [formatter formatString:#"%0C%0FRed Courier Text %1C%1FBlue Arial Text %0CRed Arial Text"];
// setup base strings
NSString *finalStr = #"Some Text. ";
NSString *shippingAttributed = [NSString stringWithFormat:#"%%B%%1C$%.2f%%b%%c", shipping];
NSString *middleText0 = #"Final price including ";
NSString *middleText1 = #" Shipping and all discount: ";
NSString *finalPriceAttributed = [NSString stringWithFormat:#"%%B%%1C$%.2f%%b%%c", finalPrice];
// Format the strings
self.label.attributedText = [formatter formatString:[NSString stringWithFormat:#"%#%#%%B%%1C%#%%b%%c%#%%B%%1C%#", finalStr, shippingAttributed, middleText0, middleText1, finalPriceAttributed];
Somewhat less code, and I think easier to understand. FYI, the formatter string in the last line contains codes that are used to modify the format of portions of the string. Those codes use double percents (

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

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

Custom NSFormatter in Objective C

I am trying to write my own custom formatter in Objective C by subclassing NSNumberFormatter. Specifically what I'd like to do is make a number turn red if it is above or below certain values. The apple documentation says
For example, if you want negative financial amounts to appear in red, you have this method return a string with an attribute of red text. In attributedStringForObjectValue:withDefaultAttributes: get the non-attributed string by invoking stringForObjectValue: and then apply the proper attributes to that string.
Based on this advice I implemented the following code
- (NSAttributedString*) attributedStringForObjectValue: (id)anObject withDefaultAttributes: (NSDictionary*)attr;
{
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[self stringForObjectValue:anObject]];
if ([[attrString string] floatValue] < -20.0f) {
[attrString addAttribute:#"NSForegroundColorAttributeName" value:[NSColor redColor] range:NSMakeRange(0, 10)];
return attrString;
} else return attrString;
}
But when I test this all it does is freeze my application. Any advice would be appreciated. Thanks.
I believe this has something to do with your NSRange that you create. I believe your length (10 in your example) is out of bounds. Try getting the length of the string that you use to initialize your NSMutableAttributedString.
For example:
- (NSAttributedString*) attributedStringForObjectValue: (id)anObject withDefaultAttributes: (NSDictionary*)attr;
{
NSString *string = [self stringForObjectValue:anObject];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSInteger stringLength = [string length];
if ([[attrString string] floatValue] < -20.0f)
{
[attrString addAttribute:#"NSForegroundColorAttributeName" value:[NSColor redColor] range:NSMakeRange(0, stringLength)];
}
return attrString;
}
Here is how I was finally able to implement this. To make it more visible when a number is negative, I decided to make the background of the text red with white text. The following code does work in a NSTextField cell. I'm not sure why the code in my question (and the answer) does not work, addAttribute should work.
- (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes: (NSDictionary *)attributes{
NSString *string = [self stringForObjectValue:anObject];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSInteger stringLength = [string length];
if ([[attrString string] floatValue] < 0)
{
NSDictionary *firstAttributes = #{NSForegroundColorAttributeName: [NSColor whiteColor],
NSBackgroundColorAttributeName: [NSColor blueColor]};
[attrString setAttributes:firstAttributes range:NSMakeRange(0, stringLength)];
}
return attrString;
}