且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UITableView,滚动后重复的图标

更新时间:2023-11-01 09:13:16

好吧,TableView正在重用单元格,并且每次显示单元格时都要添加图像.

Well the TableView is reusing the cells, and you add the image every time a cell is displayed.

因此,当重复使用单元格时,您将添加其他图像,但是已经有一个图像.

Thus when reusing the cell you add an other image, but there already is an image.

您将不得不重用图像视图,并且只有在创建单元格时才添加图像.

You will have to reuse the image view, and only add the image if you create the cell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifer = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];

    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer]autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;   


        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20,0,30,44)];
        imageView.tag = 1001;
        [cell addSubview:imageView];
        [imageView release], imageView= nil;
    }

    TabBarTestAppDelegate *delegate = (TabBarTestAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSArray *local = delegate.myData;
    // ok, it's horrible, don't look at it   :-)
    cell.textLabel.text = [NSString stringWithFormat:@"%@%@", @"       " ,[local objectAtIndex:indexPath.row]];
    //

    NSString* name = nil;;
    if (indexPath.row == 0) {
        name = @"topicon";
    }
    else if (indexPath.row + 1 == [local count]) {
        name = @"bottomicon";
    }
    else {
        name = @"innericon";
    }

    UIImageView *imageView = (UIImageView *)[cell viewWithTag:1001];
    imageView.image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:name ofType:@"png"]];

    return cell;
 }