开发者

UITableViewCell and images overlapping

i have a strange issue with my UITableView...I add a UIButton as a subview开发者_运维技巧 to each cell , but when any of the cells gets out of view something happens, and when i scroll up again , i can see that the UIButton background images of some cells are overlapping !

The cellForRowAtIndexPath method i use contains the following code , which adds the UIButton instances

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if (cell == nil)
    {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:@"MyCell"];

        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

        UIFont *titleFont = [UIFont fontWithName:@"Arial-BoldMT" size:14.0];
        [[cell textLabel] setFont:titleFont];

        [cell autorelease];


    }

    if([cell viewWithTag:indexPath.row]==nil){ 
    UIButton *buttonLeft = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonLeft.tag=indexPath.row;
    if ([[myArray objectAtIndex:indexPath.row] isEqualToString:@"item1"]) {

        [buttonLeft addTarget:self action:@selector(doThat:) forControlEvents:UIControlEventTouchUpInside];
        [buttonLeft setBackgroundImage:[UIImage imageNamed:@"item1.png"] forState:UIControlStateNormal];    
        [buttonLeft setFrame: CGRectMake( 5.0f, 6.2f, 30.0f, 30.0f)];


    }else{

        [buttonLeft addTarget:self action:@selector(doThat:) forControlEvents:UIControlEventTouchUpInside];
        [buttonLeft setBackgroundImage:[UIImage imageNamed:@"item2.png"] forState:UIControlStateNormal];    
        [buttonLeft setFrame: CGRectMake( 5.0f, 6.2f, 30.0f, 30.0f)];

    }
[cell addSubview:buttonLeft];
    }


    cell.textLabel.text=[NSString stringWithFormat:@"         %@",[myArray objectAtIndex:indexPath.row]];
    return cell;
}

Apparently , this code for some reason adds the UIButton everytime the cell is displayed. I want each button subview to be added only once.. What am i doing wrong ?

Your help is much appreciated


That is because the table view reuses cells for performance reasons. Therefore, the cellForRowAtIndexPath: method, correctly implemented like yours, returns cells that already exist and only creates a new one if there is no reusable cell available.

Put all your button-related code within if (cell == nil) {}, so that the button is only added to "fresh" cells and it should work!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜