简体   繁体   中英

change the color of label in UICollectionView iOS

hi I am working on with collection view for a calendar. I put a label in the collection view. I give the value to this label from a static array in which I add the months name. Now I have to change the color of label according to the value 0 and 1. if 1 then label turn into green and if 0 then red. These 0 and 1 values I got form the JSON. I put these values in the array.

Now my problem when I use this array in cellForItemAtIndexPath then its crash because the count of rows is 12 and the count of valueArray is 2. Is there any way to work with this. thanks..!

The problem is inconsistency in your data model.

1) Wherever your data is coming from (network, JSON..etc.) you need to end up with NSDictionary of key value pairs. Key - month Value - red or blue

2) Then in collectionView:numberOfItemsInSection: you should return number of items in dictionary like this

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
 {
    return [dictionary allKeys] count];
}

3) In your ViewController create a month mapping array. Simple NSArray that will contain 12 NSStrings - your months.

-(NSArray *)months
{
return @[@"january",
         @"february",
         @"march"
         @"april",
         @"may",
         @"june"
         @"july",
         @"august",
         @"september",
         @"october",
         @"november",
         @"december"];

}

4) Finally you will handle your concrete item in didSelectItem... by retrieving a month for a particular index..and then setting the cell to match the value for that month...and based on value you will set the color.

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //....other code here

    NSString *month = self.monthsArray[indexpath.row];
    NSString *value = self.monthsDictionary[month];

    if (value isEqualToString:@"red")
    { 
        coolectionViewCell.color = [UIColor redColor];
    }
   etc..

BONUS: You did not say what red and green means, but you really should declare an enumeration for that thing as this is a custom type. You would wrap your enums in the dictionary as NSNumbers.
Also the month mapping array is kind of rudimentary but I did not want to overwhelm you. I am sure NSDateFormatter has some kind of mechanism to play with months in a comprehensive localised way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM