Question

In my program I have a Database which consists of one entity with several attributes such as book name, current page and total page of the book. So, I want to fill tableview cell with color depending on readed pages. E.g. if I read the book by half, the cell will be filled with color also by half (curPage/totalPage*widthCell). This is my cellForRowAtIndexPath: method:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
        UITableViewCell *result = nil;
        static NSString *BookTableViewCell = @"BookTableViewCell";
        result = [tableView dequeueReusableCellWithIdentifier:BookTableViewCell];
        if (result == nil){ 
            result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:BookTableViewCell];
            result.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        Book *book = [self.booksFRC objectAtIndexPath:indexPath];
        float width = result.contentView.frame.size.width;
        double fill = ([book.page doubleValue]/[book.pageTotal doubleValue])*width;
        CGRect rv= CGRectMake(0, 0, fill, result.contentView.frame.size.height);
        UIView *v=[[UIView alloc] initWithFrame:rv];
        v.backgroundColor = [UIColor clearColor];
        v.backgroundColor = [UIColor yellowColor];
        [[result contentView] addSubview:v];
        result.textLabel.text = [book.name stringByAppendingFormat:@" %@", book.author];
        result.textLabel.backgroundColor = [UIColor clearColor];
        result.detailTextLabel.text =
        [NSString stringWithFormat:@"Page: %lu, Total page: %lu",(unsigned long)[book.page unsignedIntegerValue],(unsigned long)[book.pageTotal unsignedIntegerValue]];
        result.detailTextLabel.backgroundColor = [UIColor clearColor];
        result.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        result.textLabel.font = [UIFont systemFontOfSize:12];

        return result;
    }

The problem is when I scroll the view text disapear from that part of the cell which I painted. How can I resolve this problem?

Was it helpful?

Solution

You are adding view "v" each time. You should add it when cell is nil.

if (result == nil)
{
    result = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
                                   reuseIdentifier:BookTableViewCell];
    result.selectionStyle = UITableViewCellSelectionStyleNone;

    UIView *v=[[UIView alloc] init];
    v.tag = 1000;
    [[result contentView] addSubview:v];
    [v release];
}

UIView *v = [cell viewWithTag:1000];
//Set framme and color here..
//Do rest of the stuff
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top