Text and text color from an int value
I have four integer values: 1, 2, 3 and 4. Instead of printing the int values, I have to transform to a corresponding text.
1 -> my text 1
2 -> another text
3 -> yet another one
4 -> text 4
Also I have to change the color:
1 -> gra开发者_如何转开发y
2 -> black
3 -> blue
4 -> green
So I did this:
NSArray *myArray = [NSArray arrayWithObjects:@"",@"my text 1",@"another text", @"yet another one", @"text 4", nil];
myTextLabel.text = [myArray objectAtIndex:myInt];
But how to get the color code? Normally I do this:
myTextLabel.textColor = [UIColor greenColor];
But how can I do this with my list? And also, what is the best way to to the transformation of an integer value to a text and a text color code? Perhaps there is a better way?
Thank you in advance & Best Refards.
The same way :
NSArray *myColorArray = [NSArray arrayWithObjects: [UIColor whiteColor], [UIColor greyColor], [UIColor blueColor], [UIColor greenColor], nil];
myTextLabel.textColor = [myColorArray objectAtIndex:myInt];
For the index 0, you can't use nil, so put a color that you know you won't use.
Are these hard-coded at compile-time? If so, you might find that this works better:
static struct { NSString *text; UIColor *color; } map[] = {
{ @"my text 1" , [UIColor grayColor ] },
{ @"another text" , [UIColor blackColor] },
{ @"yet another one", [UIColor blueColor ] },
{ @"text 4" , [UIColor greenColor] },
};
Write two class methods to get the color and string for the text:
static NSArray *textColorList = nil;
static NSArray *stringList = nil;
// Creates the color list the first time this method is invoked. Returns one color object from the list.
+ (UIColor *)textColorWithIndex:(NSUInteger)index {
if (textColorList == nil) {
textColorList = [[NSArray alloc] initWithObjects:[UIColor grayColor], .., nil];
}
// Mod the index by the list length to ensure access remains in bounds.
return [textColorList objectAtIndex:(index+1) % [textColorList count]];
}
+ (NSString *)stringWithIndex:(NSUInteger)index {
if (stringList == nil) {
stringList = [[NSArray alloc] initWithObjects: @"my text 1", ... , nil];
}
return [stringList objectAtIndex:(index+1) % [stringList count]];
}
精彩评论