Storing UIColors in NSDictionary and retrieving them? - objective-c

I need to return a specific UIColor for a given index.
I am trying to basically store the UIColors as NSArrays
TypeColors = [[NSDictionary alloc] initWithObjectsAndKeys:
#"1", [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.5],[NSNumber numberWithFloat:0.5],[NSNumber
numberWithFloat:0.5],[NSNumber numberWithFloat:1.0], nil],
#"5", [NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber
numberWithFloat:0.5],[NSNumber numberWithFloat:0.1],[NSNumber
numberWithFloat:1.0], nil]
, nil]; //nil to signify end of objects and keys.
And here I want to retrieve the UIColor back from that dictionary:
a = 5;
NSArray* colorArray = [TypeColors objectForKey:a];
UIColor* color = [UIColor colorWithRed:[colorArray objectAtIndex:0]
green:[colorArray objectAtIndex:1] blue:[colorArray objectAtIndex:2]
alpha:[colorArray objectAtIndex:3]];
It always returns me a zero, anyone knows why?
Thanks!

Change it to
UIColor* color = [UIColor colorWithRed:[[colorArray objectAtIndex:0] floatValue]
green:[[colorArray objectAtIndex:1] floatValue] blue:[[colorArray objectAtIndex:2] floatValue]
alpha:[[colorArray objectAtIndex:3] floatValue]];
The parameter to be sent there is cgfloat and not NSNumber

Two things:
1) The order of things in initWithObjectsAndKeys are objects and then their keys. Yes, it is intuitively backwards.
2) The key is not an integer 5 but an NSString #"5".

You need to convert your UIcolor to Nsstring first before save it in dictionary as follow :
-(NSString *)convertColorToString :(UIColor *)colorname
{
if(colorname==[UIColor whiteColor] )
{
colorname= [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
}
else if(colorname==[UIColor blackColor])
{
colorname= [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
}
else
{
colorname=colorname;
}
CGColorRef colorRef = colorname.CGColor;
NSString *colorString;
colorString=[CIColor colorWithCGColor:colorRef].stringRepresentation;
return colorString;
}
and when you want to fetch the value from dictionary than you need to convert string to color as follow
-(UIColor *)convertStringToColor :(NSDictionary *)dicname :(NSString *)keyname
{
CIColor *coreColor = [CIColor colorWithString:[dicname valueForKey:keyname]];
UIColor *color = [UIColor colorWithRed:coreColor.red green:coreColor.green blue:coreColor.blue alpha:coreColor.alpha];
//NSLog(#"color name :%#",color);
return color;
}
exa :
here dicSaveAllUIupdate is my dictionary and i saved my view background color in it.
[dicSaveAllUIupdate setObject:[self convertColorToString: self.view.backgroundColor] forKey:#"MAINVW_BGCOLOR"];
and i will retrive it as follow
self.view.backgroundColor=[self convertStringToColor:retrievedDictionary:#"MAINVW_BGCOLOR"];
Hope this help to you ...

Related

Different Font Styles in a String in an Array

Let's say I have this:
self.dictionary = [NSMutableArray arrayWithObjects:
#"blah",
#"blah",
#"blah (blah)",
#"blah",
#"blah",
nil];
In the third object, I want to have the first "blah" with a larger font-size and a black font-color. However, I want the second "blah" with the parentheses to be of a smaller size and a grey color. How would I go about doing this? Is it even possible?
You want to use an NSMutableAttributedString.
You would simply concatenate all yours strings and for each substring, figure what attributes you want, than call - setAttributes:range:.
NSString doesn't allow you to have specific style. If your string need to have style/attributes, you will have to use NSAttributedString.
Right now you store just NSString objects. NSString doesn't have any font attached to it. If you want to keep font information - you can take a look at NSAttributedString class - https://developer.apple.com/Library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/index.html
So your code would look like:
self.items = #[
[[NSAttributedString alloc] initWithString: #"bla" attributes: #{
NSFontAttributeName: [UIFont systemFontOfSize: 12.0],
NSForegroundColorAttributeName: [UIColor blackColor]
}],
[[NSAttributedString alloc] initWithString: #"bla" attributes: #{
NSFontAttributeName: [UIFont systemFontOfSize: 14.0],
NSForegroundColorAttributeName: [UIColor grayColor]
}]
];
Try below code:-
NSArray *yourArr= #[#"blah",
#"blah",
#"blah (blah)",
#"blah",
#"blah"];
for (NSString *word in yourArr)
{
if ([word isEqualToString:#"blah (blah)"])
{
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:[word componentsSeparatedByString:#" "][0] attributes:#{NSFontAttributeName:[NSFont boldSystemFontOfSize:18]}]];
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:#" "]];
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:[word componentsSeparatedByString:#" "][1] attributes:#{NSFontAttributeName:[NSFont boldSystemFontOfSize:14],NSForegroundColorAttributeName:[NSColor grayColor]}]];
}
else
{
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:word]];
}
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:#",\n"]];
}
self.yourAttStr=yourAtt;

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)

Store and get UIColor from .plist file

I've been searching for this for a while now with no success. My question is: is there an easy way to store and get UIColors such as [UIColor blackColor] or [UIColor colorWithRed:0.38 green:0.757 blue:1 alpha:1]; in a .plist file in my app directory?
according to this discussion you have two options:
Store it like NSData in Data field of .plist file
Store it like String UIColor representation
NSData option
NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:[UIColor greenColor]];
NSString option
NSString *color = #"greenColor";
[UIColor performSelector:NSSelectorFromString(color)]
read more here: http://www.iphonedevsdk.com/forum/iphone-sdk-development/27335-setting-uicolor-plist.html
If you want to keep it human readabe,
I did a category for this:
#implementation UIColor (EPPZRepresenter)
NSString *NSStringFromUIColor(UIColor *color)
{
const CGFloat *components = CGColorGetComponents(color.CGColor);
return [NSString stringWithFormat:#"[%f, %f, %f, %f]",
components[0],
components[1],
components[2],
components[3]];
}
UIColor *UIColorFromNSString(NSString *string)
{
NSString *componentsString = [[string stringByReplacingOccurrencesOfString:#"[" withString:#""] stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray *components = [componentsString componentsSeparatedByString:#", "];
return [UIColor colorWithRed:[(NSString*)components[0] floatValue]
green:[(NSString*)components[1] floatValue]
blue:[(NSString*)components[2] floatValue]
alpha:[(NSString*)components[3] floatValue]];
}
#end
The same formatting that is used by NSStringFromCGAffineTransform. This is actually a part of a bigger scale plist object representer in [eppz!kit at GitHub][1].
The best and readable way in Objective-c is to save it as hex string like: "#1A93A8", then to get it by extern method;
in .h file:
extern UIColor *colorFromHEX(NSString *hex);
extern NSString *HEXFromColor(UIColor *color);
in .m file:
UIColor *colorFromHEX(NSString *hex){
NSString *stringColor = hex;
int red, green, blue;
sscanf([stringColor UTF8String], "#%02X%02X%02X", &red, &green, &blue);
UIColor *color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
return color;
}
NSString *HEXFromColor(UIColor *color){
const CGFloat *components = CGColorGetComponents(color.CGColor);
size_t count = CGColorGetNumberOfComponents(color.CGColor);
if(count == 2){
return [NSString stringWithFormat:#"#%02lX%02lX%02lX",
lroundf(components[0] * 255.0),
lroundf(components[0] * 255.0),
lroundf(components[0] * 255.0)];
}else{
return [NSString stringWithFormat:#"#%02lX%02lX%02lX",
lroundf(components[0] * 255.0),
lroundf(components[1] * 255.0),
lroundf(components[2] * 255.0)];
}
}
in any where
NSDictionary *Config = [[NSDictionary alloc] initWithContentsOfFile:[NSBundle.mainBundle pathForResource:#"Config" ofType:#"plist"]];
UIColor *color = colorFromHEX( Config[#"color"] );
NSString *strColor = HEXFromColor( UIColor.blackColor );

How would I output this array of strings?

Say I had an array of strings...
[NSArray arrayWithObjects: #"red", #"blue", #"green", #"yellow", nil]
how would I achieve an output like this...?
red is a color
blue is a color
green is a color
yellow is a color
Thanks!
NSArray *colors = ...;
for (NSString *color in colors) {
NSLog(#"%# is a color", color);
}
NSArray *initializedNSArray = [NSArray arrayWithObjects: #"red",
#"blue",
#"green",
#"yellow",
nil]
for( int i=0; i<4; ++i )
NSLog(#"%# is a color \n", [initializedNSArray objectAtIndex: i];
// ^^^^^^^^^^^^^^^^^ to array it is earlier initialized to

Getting CGRect from array

For my application I am trying to store CGRect objects into an NSMutableArray. It is loading well and printing in the log statement, but trying to take the CGRects from the array shows an error. Here is a code snippet:
CGRect lineRact = CGRectMake([[attributeDict objectForKey:#"x"] floatValue],
[[attributeDict objectForKey:#"y"] floatValue],
[[attributeDict objectForKey:#"width"] floatValue],
[[attributeDict objectForKey:#"height"] floatValue]);
[lineRactangle addObject:NSStringFromCGRect(lineRact)];
How can I get the rects back from the array?
A CGRect is a struct, not an object, and thus cannot be stored in NSArrays or NSDictionaries. You can turn it into a string and turn that string back into a CGRect, but the best way is to encapsulate it via an NSValue:
NSValue *myValue = [NSValue valueWithCGRect:myCGRect];
You can then store this NSValue object in arrays and dictionaries. To turn it back into a CGRect, you'd do:
CGRect myOtherCGRect = [myValue CGRectValue];
[lineRactangle addObject:[NSValue valueWithCGRect:lineRect]];
Use NSValue to wrap CGRect thus store them in NSArrays.
For example:
CGRect r = CGRectMake(1,2,3,4);
NSValue *v = [NSValue valueWithCGRect:rect];
NSArray *a = [NSArray arrayWithObject:v];
CGRect r2 = [[a lastObject] CGRectValue];
See documentation for the other supported structures.
Actually, I don't think any of the answers thus far really address the question ajay asked. The short answer is: You need to supply CGRectMake with the intValue, rather than the floatValue of the dictionary item. If you need to do this for several CGRects, here's a suggested method:
- (CGRect) NSArrayToCGRect: (NSDictionary *) attributeDict
{
int x = [[attributeDict objectForKey:#"x"] intValue];
int y = [[attributeDict objectForKey:#"y"] intValue];
int w = [[attributeDict objectForKey:#"width"] intValue];
int h = [[attributeDict objectForKey:#"height"] intValue];
return CGRectFromString([NSString stringWithFormat: #"{{%d,%d},{%d,%d}}", x, y, w, h]);
}
There may be a more elegant way to accomplish this, but the above code does work.
If your object can be set with ".frame" you could use:
// {{CGFloat x,CGFloat y}, {CGFloat width,CGFloat height}}
NSString *objectCoords = #"{{116,371},{85,42}}";
myObject.frame = CGRectFromString(objectcoords);
or for multiple objects:
NSArray *objectCoords = [NSArray arrayWithObjects:
#"{{116,371},{85,42}}",
#"{{173,43},{85,42}}",
#"{{145,200},{85,42}}",
nil];
myObject1.frame = CGRectFromString([objectCoords objectAtIndex:0]);
myObject2.frame = CGRectFromString([objectCoords objectAtIndex:1]);
myObject3.frame = CGRectFromString([objectCoords objectAtIndex:2]);
CGRect is a struct you cannot put it in an NSArray. You can only add objects to it.
or something more 'extreme'... creating an array that holds arrays of CGRect(s)
movPosTable = [[NSArray alloc] initWithObjects:
[[NSArray alloc] initWithObjects: [NSValue valueWithCGRect:[GridAB frame]], [NSValue valueWithCGRect:[GridBA frame]], [NSValue valueWithCGRect:[GridBB frame]], nil],
[[NSArray alloc] initWithObjects: [NSValue valueWithCGRect:[GridAA frame]], [NSValue valueWithCGRect:[GridAC frame]], [NSValue valueWithCGRect:[GridBA frame]], [NSValue valueWithCGRect:[GridBB frame]], [NSValue valueWithCGRect:[GridBC frame]], nil],
[[NSArray alloc] initWithObjects: [NSValue valueWithCGRect:[GridAB frame]], [NSValue valueWithCGRect:[GridBB frame]], [NSValue valueWithCGRect:[GridBC frame]], nil], nil];
where 'GridAA', 'GridAB' etc. correspond to UIViews