NSMutableArray from plist key values separated by comma - iphone

I have a plist file that stores cached colors, it looks like this
<key>CachedColors</key>
<dict>
<key>com.Halfbrick.Fruit</key>
<string>0.00000,0.00000,0.00000</string>
<key>com.apple.Preferences</key>
<string>0.28824,0.37059,0.48235</string>
</dict>
what I want to do is use the 3 values to create a UIColor, the UIColor will change depending on the bundle id, the values are for Red, Green, and Blue
but I'd want the UIColor to change automatically if the bundle id changes, I'm using it as the background color for the banners, and say if I'm on the home screen and get a notification, the background is white, but if I open the Settings app I'd want it to change to the RGB value for com.apple.Preferences from the plist sort of how in iOS 6 the status bar background changes automatically when opening an app to match the UINavigationBar
I used:
SBApplication *frontApp = [(SpringBoard*)[UIApplication sharedApplication] _accessibilityFrontMostApplication];
NSDictionary *statusBarCachedColors = [NSDictionary dictionaryWithContentsOfFile:#"/var/mobile/Library/Preferences/cc.tweak.statuscolor.plist"];
NSString *colorString = [statusBarCachedColors objectForKey:frontApp];
NSArray *components = [colorString componentsSeparatedByString:#","];
UIColor *tintColor = [UIColor colorWithRed:[components[0] floatValue] green:[components[1] floatValue] blue:[components[2] floatValue] alpha:1.0];
I am developing for a jailbroken device

After you pick up that string from the plist:
NSArray *components = [string componentsSeparatedByString:#","];
UIColor *color = [UIColor colorWithRed:[components[0] floatValue] green:[components[1] floatValue] blue:[components[2] floatValue] alpha:1];
... Or on older compiler
UIColor *color = [UIColor colorWithRed:[[components objectAtIndex:0] floatValue]
green:[[components objectAtIndex:1] floatValue]
blue:[[components objectAtIndex:2] floatValue] alpha:1];
If the question includes something else, it's hard to follow the punctuation

Related

Color String in the Label

If I want to create some strings having format as these:
the string is the text property of a label.
some characters in this string have color different from other characters.
some characters are underlined and have a link, and when I hit the characters, and other views pop up.
Could somebody tell me how can I realize this effect?
If you support iOS < 6, better use 3rd party component e.g. TTTAttributedLabel. Else use attributedText property of UILabel.
NSDictionary *colors = [[NSDictionary alloc] initWithObjectsAndKeys: [UIColor blueColor], #"Hyd", [UIColor brownColor], #"Bang", [UIColor orangeColor], #"Delhi", [UIColor yellowColor], #"Gujarat", nil];
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:#""];
for (NSString *word in colors) {
UIColor *color = [colors objectForKey:word];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
NSAttributedString *substring = [[NSAttributedString alloc] initWithString:word attributes:attributes];
[attributeString appendAttributedString:substring];
}

Make the specific string Pattern bold and blue in UILable

i have a program in which i get a tweets from twitter and show them in UITableviewcell. now problem is that i have to make a all twitter names bold and bule and show them in the orginal tweet with bule and bold names.
For Example i have tweet like this
MT #OraTV: SNEAK PEEK: #tomgreenlive #TheoVon & #DavidBegnaud talk Miley's #twerking #Batfleck &more on
so all the names starting with # should be bold and bule.
i use this code to extract All names starting with # but not know how to bold them and show
them in single uitableviewcell
NSString * aString =twitterMessage
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:#"#" intoString:nil];
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:#"#" intoString:nil];
if([scanner scanUpToString:#" " intoString:&substring]) {
[substrings addObject:substring];
}
[scanner scanUpToString:#"#" intoString:nil];
}
you have to build an NSAttributedString by swiping between 2 fonts and colors.
If you're able to detect them, you should probably replace your names by surrounding them with a known markup (eg: #aName). Then, parse the string to build a NSAttributedString.
You can use this code (not tested, you'll probably have to tweak):
// String to parse
NSString *markup = #"MT <color>#OraTV</color>: SNEAK PEEK: <color>#tomgreenlive</color>...";
// Names font and color
UIFont *boldFont = [UIFont boldSystemFontOfSize:15.0f];
UIColor *boldColor = [UIColor blueColor];
// Other text font and color
UIFont *stdFont = [UIFont systemFontOfSize:15.0f];
UIColor *stdColor = [UIColor blackColor];
// Current font and color
UIFont *currentFont = stdFont;
UIColor *currentColor = stdColor;
// Parse HTML string
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:#""];
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:#"(.*?)(<[^>]+>|\\Z)"
options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators
error:nil];
NSArray *chunks = [regex matchesInString:markup options:0 range:NSMakeRange(0, [markup length])];
for (NSTextCheckingResult* b in chunks)
{
NSArray *parts = [[markup substringWithRange:b.range] componentsSeparatedByString:#"<"];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:currentFont,NSFontAttributeName,currentColor,NSForegroundColorAttributeName,nil];
[aString appendAttributedString:[[NSAttributedString alloc] initWithString:[parts objectAtIndex:0] attributes:attrs]];
if([parts count] > 1)
{
NSString *tag = (NSString *)[parts objectAtIndex:1];
if([tag hasPrefix:#"color"])
{
currentFont = boldFont;
currentColor = boldColor;
}
else if([tag hasPrefix:#"/color"])
{
currentFont = stdFont;
currentColor = stdColor;
}
}
}
Hope that helps.
Cyril
So you have all the names properly extracted already? If so, it seems like NSAttributedString is what you want. More information here.
Something like this: [str setTextColor:[UIColor blueColor] range:NSMakeRange(0,5)];
For bold text, use [UIFont boldSystemFontOfSize:fontSize]. See example in the second link above.

CFAttributedString replace occurrences of string?

I know that in a CFAttributedString does not respond to any method like the stringByReplacingOccurrencesOfString:withString: method of NSString, and I cannot find a method that can do that using a CF(Mutable)AttributedString.
I want to replace some text in the string with the same text but another color, e. g., I have the string #"This is a text" and I want to change the color of the word "text".
I hope the question is clear enough, if it isn't, ask me.
Thanks.
I would add a category on NSMutableAttributedString:
#implementation NSMutableAttributedString (MySearchAndReplaceCategory)
- (void)setAttributes:(NSDictionary *)attributes forOccurencesOfString:(NSString *)target
{
NSRange searchRange = NSMakeRange(0, self.length);
while ( searchRange.length )
{
NSRange range = [self.string rangeOfString:target options:0 range:searchRange];
if ( ! range.length )
break;
[self setAttributes:attributes range:range];
searchRange.length = NSMaxRange(searchRange) - NSMaxRange(range);
searchRange.location = NSMaxRange(range);
}
}
#end
Then use something like that:
UIColor *color = [UIColor greenColor];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:(__bridge id) color.CGColor
forKey:(__bridge id) kCTForegroundColorAttributeName];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:#"This is a text"];
[text setAttributes:attributes forOccurencesOfString:#"text"];
re: Toll-Free Bridging
CFAtttributeString and NSAttributeString have different attributes keys.
Ex. Color Mac OS X:
NSForegroundColorAttributeName - NSColor - Default blackColor
kCTForegroundColorAttributeName - The value associated with this attribute must be a CGColor object. Default value is black.

storing uicolor in plist

I am trying to store UIColor in plist.I seen many links but none of those not given accurate answer.some of my sample code is below
CGColorRef color=[MyColor CGColor];
NSUInteger numComponents = CGColorGetNumberOfComponents(color);
const CGFloat *components=CGColorGetComponents(color);
NSArray *colorArray=[NSArray arrayWithObjects:(float)components[0],(float)components[1],nil];
it is giving Not working for me can any one tell me the exact answer to store uicolor into plist.Thanks in advance.Your suggestion is important for me.Please provide sample snippet rather than posting links.
You would need to store the individual colors separately (RGBA, if that is the color space you are using) in an array of NSNumbers.
NSNumber *red = [NSNumber numberWithFloat:components[0]];
NSNumber *green = [NSNumber numberWithFloat:components[1]];
NSNumber *blue = [NSNumber numberWithFloat:components[2]];
NSNumber *alpha = [NSNumber numberWithFloat:components[3]];
NSArray *colors = [NSArray arrayWithObjects:red, green, blue, alpha, nil];
The reason for this is that you can only add objects to a NSArray. A float or CGFloat is not an object.

iPhone UIColor in Plist file

Is that possible to save colorcodes in Plist file somehow?
Do I have to represent them in string? and then can I create colors from them?
I saw a similar thread here about this but it has no answer yet
What could be done?
I can give you a suggestion. Instead of storing the color names you can store the RGB values in a array and store that array in each row in the plist.
key - Red
Type - Array
value - 1.0,0.0,0.0
Retrieve the array for each key.
NSArray *colorsArray = [dictionaryFromPlist objectForKey:#"Red"];
UIColor *mycolor = [UIColor colorWithRed:[[colorsArray objectAtIndex:0] floatValue]
green:[[colorsArray objectAtIndex:1] floatValue]
blue:[[colorsArray objectAtIndex:2] floatValue]
alpha:1.0];
Just my thought..
UIColor (see here) conforms to the NSCoding protocol (see here) meaning you can write them out to a plist if you do it using NSCoding.
There is a great tutorial here about saving and restoring your app data using NSCoding
You can use NSKeyedArchiver which inherits from NSCoder
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[UIColor purpleColor]];
[[NSUserDefaults standardUserDefaults] registerDefaults:#{#"color": data}];
To get the color back out you would use NSKeyedUnarchiver:
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
NSLog(#"%#", [NSKeyedUnarchiver unarchiveObjectWithData: dict[#"color"]]);
To preserve human readability, 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].