UICollectionView设置特定位置indexPath.row的背景

时间:2014-09-30 02:00:50

标签: ios objective-c uicollectionview

使用UICollectionView的iOS工作天气应用程序相当新,其中最冷的小时预测将具有蓝色背景渐变,最热的小时将具有橙色背景渐变。

我创建的逻辑是我在最冷和最热的数组中识别位置,然后将其与indexPath.row匹配以设置适当的渐变。但是,它只能工作一次。当我滚动或切换视图时,似乎渐变是随机分配的。当我NSLog记录低/高温和indexPath.row时,它们似乎与预期的一样。

这是我的代码:

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"ConditionsCell";

ConditionsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

cell.conditionsTime.text = [self.hours objectAtIndex:indexPath.row];
cell.conditionsTemp.text = [NSString stringWithFormat:@"%@°", [self.hoursTemp objectAtIndex:indexPath.row]];
cell.conditionsImage.image = [UIImage imageNamed:@""]; //resetting image

NSLog (@"indexPath %d self.lowTempPosition %d", indexPath.row, self.lowTempPosition);

if(indexPath.row == self.lowTempPosition)
{
CAGradientLayer *gradientBlue = [CAGradientLayer layer];
gradientBlue.frame = cell.bounds;
gradientBlue.colors = [NSArray arrayWithObjects:(id)[[Utils beginBlue] CGColor], (id)[[Utils endBlue] CGColor], nil];
[cell.contentView.layer insertSublayer:gradientBlue atIndex:0];
}
else if (indexPath.row == self.highTempPosition)
{
    CAGradientLayer *gradientBlue = [CAGradientLayer layer];
    gradientBlue.frame = cell.bounds;
    gradientBlue.colors = [NSArray arrayWithObjects:(id)[[Utils beginOrange] CGColor], (id)[[Utils endOrange] CGColor], nil];
    [cell.contentView.layer insertSublayer:gradientBlue atIndex:0];
}
else
{
    CAGradientLayer *gradientWhite = [CAGradientLayer layer];
    gradientWhite.frame = cell.bounds;
    gradientWhite.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
    [cell.ContentView.layer insertSublayer:gradientWhite atIndex:0];
}

     NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:[self.hoursIcons objectAtIndex:indexPath.row]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    @autoreleasepool {//autorelease pool for memory release
        if (!error) {

            dispatch_async(dispatch_get_main_queue(), ^{
                cell.conditionsImage.image = [UIImage imageWithData: data];//update UI

            });

        }}//autorelease pool

}];


[dataTask resume];

return cell;
 }

1 个答案:

答案 0 :(得分:1)

问题在于细胞的重复使用。您正在将渐变添加为单元格contentView的子图层。所以在滚动时,子层仍然存在。就像您要重置图像一样,您也应该重置图层。最快的方法是打电话:

cell.contentView.layer.sublayers = nil;

这应该重置图层,然后您可以再次添加所需的温度梯度。