开发者

Adding UIImageView dynamically in UITableViewCell

I am using a UITableView to display some information about the consequences of driving to fast: What the fine is going to be etc. I also use so开发者_StackOverflowme red "dots" that you get in your driving licence. Since this can be between 0 - 6 for each row I have done the following:

- (UITableViewCell *)tableView:cellForRowAtIndexPath:

// Code if no cell is available in the que

// End of that code

UIImage *seniorImage = [UIImage imageNamed:@"ticket_dot.png"];

if (seniorDots == 0) {

} else {
    for (int i = 0; i < seniorDots; i++) {
        UIImageView *seniorImageView = [[UIImageView alloc] initWithFrame:CGRectMake(40.0 + (i * 15.0), 40.0, 15.0, 40.0)];
        seniorImageView.image = seniorImage;
        seniorImageView.contentMode = UIViewContentModeCenter;
        [cell.contentView addSubview:seniorImageView];
        [seniorImageView release];
    }
}

seniorDots is a variable that I get from a plist file. The code is working as intended but as you may see I have no way of removing them. So the first time I open the tableview I see the expected view, but if I scroll up again the code just keep adding UIImageViews on the cell, not removing the old ones. How can I reference these dots to remove them from screen before adding new ones?


 UITableViewCell *cell = (UITableViewCell *)[tableView    dequeueReusableCellWithIdentifier:CellIdentifier];

UIImageView *imgView; 
if(cell == nil)
{
   cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero         reuseIdentifier:CellIdentifier] autorelease];

 imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100,0,100,62)];
[imgView setImage:[UIImage imageNamed:@"img.png"]];
imgView.tag = 55;
[cell.contentView addSubview:imgView];
[imgView release];
} 
else
{
    imgView = (id)[cell.contentView viewWithTag:55];
}


You can put below code inside your cellForRowAtIndexPath method:

//Remove Other Data

   for (UIImageView *img in cell.contentView.subviews) {
        if ([img isKindOfClass:[UIImageView class]]) {
            [img removeFromSuperview];
        }
    }

I hope it will be helpful to you. Let me know in case of any difficulty.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜