How to change colors of a label in iphone sdk?
i am using one for loop for creating labels those are having text stored in nsarray.I want to display 1st labeltext color red and 2nd labeltext white and 3rd red ,4th white,5th red and 6th white ..........etc for all the labe开发者_高级运维ls that are stored in an array how to do this.help me on that ..can anyone shathanks in advance
If you want to alternate between two colors the simplest thing is to use the modulo operator (%) to figure out if you are on an even or odd label index.
Here is one way of doing this:
int labelIndex = 0;
for (NSString *labelText in labelArray)
{
UILabel *label = [[[UILabel alloc] init] autorelease];
label.text = labelText;
label.textColor = (labelIndex % 2) ? [UIColor whiteColor] : [UIColor redColor];
// Do something with the label here.
labelIndex++;
}
You can also use this technique to alternate between more than two different colors, but then I would suggest that you put the colors into an array of their own and index that array using (labelIndex % numColors) or something similar.
After you create a uilabel you can set the background color:
myLabel.backgroundcolor = [UIColor clearcolor]; // Specify what you want the
background color to be.
myLabel.textColor = [UIColor whiteColor]; // specify the text color for this property.
Give tags to labels starting from 1 and then just use this method.
for(int i=1;i<=[array count];i++)
{
UILabel *label = [[UILabel alloc] init];
label.tag = i;
[label setFrame:<your-frame>];
if(label.tag % 2 == 1)
{
[label setBackgoundColor:[UIColor blackColor]]; // This line may be optional for you
[label setTextColor:[UIColor redColor]];
}
else if(label.tag % 2 == 0)
{
[label setBackgoundColor:[UIColor blackColor]]; // This line may be optional for you
[label setTextColor:[UIColor whiteColor]];
}
}
Hope this helps you.
you can store UIColor objects in array and set on label while you set text from array in your loop. like this
label.textColor = [ColorsArray objectAtIndex:loopConuter];
You mean that you want to set colors on an array that is not constant sized? maybe you can accomplish it with
[UIColor colorWithRed:<#(CGFloat)#> green:<#(CGFloat)#> blue:<#(CGFloat)#> alpha:<#(CGFloat)#>]
it takes 4 float values from 0 to 1, maybe you don't need the transparency. then you could write a function, which takes 1 int value and outputs 3 float values. if you don't really want to have the colors set in a definite order, maybe you can generate 3 random numbers and than transform them into [0,1]
精彩评论