通过表格单元格+ iOS中的循环以编程方式添加图像 [英] adding images programmatically via loop in table cell + iOS

查看:91
本文介绍了通过表格单元格+ iOS中的循环以编程方式添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用程序来显示列表,每个列表都有x个图像显示在表格单元格中。

I am creating an app to display listings and each listing has x number of images to be displayed in table cell.

要显示图像,我必须创建UIImageView动态地在一个for循环中加载单元格中的图像{取决于从服务器调用收到的数据}。

To display the images, i have to create the UIImageView dynamically and load the images in the cell in a for loop {depending on the data received from a server call}.

现在,我可以添加图像动态但单元格中显示的图像数量不正确。我已经检查了数组值和循环次数,但仍然无法理解为什么图像没有正确加载。

Now, i am able to add the images dynamically but the number of images displayed in cell is not correct. I have checked the array value and count of loop but still not able to understand that why images are not loading properly.

问题:
前3-4个单元格在加载视图时加载的内容显示了以编程方式添加的图像视图的正确数量。但是当我滚动到表格底部时,单元格中没有显示正确数量的图像并显示随机数量的图像

PROBLEM : first 3-4 cell that are loaded as the view is loaded shows correct number of programmatically added image views. But when i scroll to bottom of the table, the correct number of images are not displayed in the cell and shows random number of images

这里是功能代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *Cellidentifier1 = @"VenueCell";
VenueCell *cell = [tableView dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];

// Configure the cell...

long row = [indexPath row];

if (!cell.hasImageViews) {
    cell.hasImageViews = YES;
    NSArray *individualSports = [_venueSports[row] componentsSeparatedByString:@"|"] ;

    NSLog(@"sports132431 = %@",individualSports);
    for (int t = 0; t<individualSports.count; t++) {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((250/10*t+10), 125, 20, 20)];
        if ([individualSports[t] isEqual:@"Cricket"]) {
            [imageView setImage:[UIImage imageNamed:@"cricket_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Basketball"]) {
            [imageView setImage:[UIImage imageNamed:@"basketball_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Football"]) {
            [imageView setImage:[UIImage imageNamed:@"football_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Lawn Tennis"]) {
            [imageView setImage:[UIImage imageNamed:@"lawn_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Squash"]) {
            [imageView setImage:[UIImage imageNamed:@"squash_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Table Tennis"]) {
            [imageView setImage:[UIImage imageNamed:@"table_unselected.png"]];
        }  else if ([individualSports[t] isEqual:@"Badminton"]) {
            [imageView setImage:[UIImage imageNamed:@"badminton_unselected.png"]];
        }  else if ([individualSports[t] isEqual:@"Pool"]) {
            [imageView setImage:[UIImage imageNamed:@"pool_unselected.png"]];
        }  else if ([individualSports[t] isEqual:@"Swimming"]) {
            [imageView setImage:[UIImage imageNamed:@"swiming_unselected.png"]];
        }
        [cell addSubview:imageView];
    }
    individualSports = [[NSArray alloc] init];
    NSLog(@"sports = %@",_venueSports[row]);
    NSLog(@"asx=%@",individualSports);
}


return cell;

}

// hasImageViews是VenueCell类的bool变量

// hasImageViews is a bool variable of VenueCell class

任何建议都是好的。
提前致谢!

Any suggestion is good. Thanks in advance!

更新:以下是更新后的代码:

Update: Here is the updated code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

long row = [indexPath row];
// Configure the cell...

long row = [indexPath row]; 
cell.vName.text = _venueName[row];
cell.vTiming.text = _venueTiming[row];
cell.vAreaName.text = _venueArea[row];
cell.starRatingImage.backgroundImage=[UIImage imageNamed:@"starsbackground iOS.png"];
cell.starRatingImage.starImage = [UIImage imageNamed:@"star.png"];
cell.starRatingImage.starHighlightedImage = [UIImage imageNamed:@"starhighlighted.png"];
cell.starRatingImage.maxRating = 5.0;
cell.starRatingImage.delegate = self;
cell.starRatingImage.horizontalMargin = 12;
cell.starRatingImage.editable=NO;
cell.starRatingImage.rating=[_venueAvgRating[row] floatValue] ;
cell.starRatingImage.displayMode=EDStarRatingDisplayAccurate;




NSArray *individualSports = [_venueSports[row] componentsSeparatedByString:@"|"] ;

for (int t = 0; t<individualSports.count; t++) {
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((25*t+10), 125, 20, 20)]; 

    // Since each of your individualSports[t] options
    // first words is simply the prefix to your image file name,
    // you can simplify the contents of your loop like so:
    NSString *firstWord = (NSString*)[[individualSports[t] componentsSeparatedByString:@" "] objectAtIndex:0];
    [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_unselected.png", firstWord.lowercaseString]]];

    [cell addSubview:imageView];
} 
if([_venueCategory[row] isEqualToString:@"Partner"]){ 

    cell.vImageCategory.image=[UIImage imageNamed:@"venue_partner.png"];
} 
else if([_venueCategory[row] isEqualToString:@"Verified"]){
    cell.vImageCategory.image=[UIImage imageNamed:@"venue_verified.png"];
} 
else{ 

    cell.vImageCategory.image=[UIImage imageNamed:@"venue_unverified.png"];
}
cell.vImage.image=[UIImage imageNamed:@"agon_logo.png"];



return cell;

}


推荐答案

首先关闭,因为你正在重复使用你的单元格,这个比较 - if(!cell.hasImageViews){ - 不一定能为 cellForRowAtIndexPath 的当前单元格,因为重用的单元格可能与当前单元格不同。例如,如果表格视图中的4个单元格可以同时适合您的屏幕,当您滚动到最初离开表格的单元格5时,重复使用它意味着它包含单元格1的内容和属性值。因此,比较是完全不相关。

First off, since you're reusing your cells, this comparison -- if (!cell.hasImageViews) { -- won't necessarily hold the appropriate value for cellForRowAtIndexPath's current cell since the cell that's being reused can be different from the current cell. For example, if 4 cells of your table view can fit on your screen at once, when you scroll to cell 5 which was originally off the table, reusing it means that it contains the contents and property values of cell 1. So that comparison is completely irrelevant.

在这种特殊情况下,重复使用单元格没有任何意义,因为单元格的整个内容对于每一行都是完全不同的。此外,由于您的自定义表格视图单元格似乎只包含 .hasImageViews 属性,因此在这种情况下不需要使用自定义单元格,因为正如我们已经建立的那样,我们赢了不要重复使用单元格。

In this specific case though, it makes no sense whatsoever to reuse your cells since the entire contents of the cells are completely different for each row. Also, since your custom table view cell seems to only contain the .hasImageViews property, using a custom cell is unnecessary in this case since, as we've already established, we won't be reusing the cells.

最后,您可以大大简化for循环中的条件,就像我在下面的代码中所做的那样。

Lastly, you can greatly simplify the conditionals within your for loop as I've done in my code below.

为了实现这些变化,我建议做这样的事情:

To implement these changes, I recommend doing something like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

    long row = [indexPath row];

    NSArray *individualSports = [_venueSports[row] componentsSeparatedByString:@"|"] ;

    for (int t = 0; t<individualSports.count; t++) {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((25*t+10), 125, 20, 20)];

        // Since each of your individualSports[t] options
        // first words is simply the prefix to your image file name,
        // you can simplify the contents of your loop like so:
        NSString *firstWord = (NSString*)[[individualSports[t] componentsSeparatedByString:@" "] objectAtIndex:0];
        [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_unselected.png", firstWord.lowercaseString]]];

        [cell addSubview:imageView];
    }

    return cell;

}

(注意:你拼错了游泳错误文件名,因此如果您不编辑捆绑包中的文件名,我对您的条件所做的更改将不适用于该条件。)

(Note: You've spelled "swimming" incorrectly in the file name so the change I made to your conditional won't work for that one if you don't edit the file name in your bundle.)

更新现在从您的更新代码中可以清楚地看到, VenueCell 除了原始问题中显示的属性之外还有其他属性,因此重用您的单元格可能有意义毕竟。要做到这一点,你必须在每次调用 cellForRowAtIndexPath 时清除旧的 UIImageView 子视图,例如:

Update: As is now clear from your updated code, VenueCell had other properties beyond the ones apparent in your original question, so perhaps it makes sense to reuse your cells after all. To do that though, you'll have to clear out your old UIImageView subviews during each call to cellForRowAtIndexPath, ex:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *Cellidentifier1 = @"VenueCell";
    VenueCell *cell = [tableView dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];

    long row = [indexPath row];

    cell.vName.text = _venueName[row];
    cell.vTiming.text = _venueTiming[row];
    cell.vAreaName.text = _venueArea[row];
    cell.starRatingImage.backgroundImage=[UIImage imageNamed:@"starsbackground iOS.png"];
    // ... all the other starRatingImageCode ...
    cell.starRatingImage.displayMode=EDStarRatingDisplayAccurate;

    // Clear out any images previously added to the
    // cell during cellForRowAtIndexPath (images have been
    // assigned a tag of 1000 in the next for loop)
    for (UIView *subview in cell.subviews) {
        if (subview.tag == 1000) {
            [subview removeFromSuperview];
        }
    }

    NSArray *individualSports = [_venueSports[row] componentsSeparatedByString:@"|"] ;

    for (int t = 0; t<individualSports.count; t++) {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((25*t+10), 125, 20, 20)];
        imageView.tag = 1000 //<-- Use a tag unique to these image views

        NSString *firstWord = (NSString*)[[individualSports[t] componentsSeparatedByString:@" "] objectAtIndex:0];
        [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_unselected.png", firstWord.lowercaseString]]];

        [cell addSubview:imageView];
    }

    // Assuming the only "else" condition is "default",
    // I've similarly simplified this code as I did with
    // your other conditional
    cell.vImageCategory.image = [NSString stringWithFormat:@"venue_%@.png", _venueCategory[row].lowercaseString];
    cell.vImage.image = [UIImage imageNamed:@"agon_logo.png"];

    return cell;
}

这篇关于通过表格单元格+ iOS中的循环以编程方式添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆