UITableView滚动不稳定

时间:2012-08-27 08:32:16

标签: objective-c ios cocoa-touch

这是我的cellForRowAtIndexPath方法。在我的项目中使用ARC。

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

    static NSString* cellIdentifier = @"ActivityCell";



    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (!cell) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];

    }



    Activity* activityToShow = [self.allActivities objectAtIndex:indexPath.row];



    //Cell and cell text attributes

    cell.textLabel.text = [activityToShow name];


    //Slowing down the list scroll, I guess...

    LastWeekView* lastWeekView = [[LastWeekView alloc] initWithFrame:CGRectMake(10, 39, 120, 20)];

    [lastWeekView setActivity:activityToShow];

    lastWeekView.backgroundColor = [UIColor clearColor];

    [cell.contentView addSubview:lastWeekView];



     return cell;

}

LastWeelView分配正在减慢我猜的滚动速度。在lastWeekView中,我从CoreData获取实体的关系,对这些值执行计算并在其drawRect方法中绘制一些颜色。

这是LastWeekView的drawRect

- (void)drawRect:(CGRect)rect
{
    NSArray* activityChain = self.activity.computeChain; //fetches its relationships data


    for (id item in activityChain) {
        if (marking == [NSNull null]) 
        {
            [notmarkedColor set];
        }
        else if([(NSNumber*)marking boolValue] == YES)
        {
            [doneColor set];
        }
        else if([(NSNumber*)marking boolValue] == NO)
        {
            [notdoneColor set];
        }

        rectToFill = CGRectMake(x, y, 10, 10);
        CGContextFillEllipseInRect(context, rectToFill);

        x = x + dx;
    }
}

我可以做些什么来平滑tableView的滚动?如果我必须将lastWeekView异步添加到每个单元格的contentView,我该怎么办?请帮忙。

1 个答案:

答案 0 :(得分:1)

我建议在单元格的分配范围中分配LastWeekView。另外 - 获取viewDidLoad中的所有核心数据对象,以便在cellForRowAtIndexPath:方法中从数组中检索它,而不是从存储中检索它。看起来应该是这样的:

- (void)viewDidLoad
    ...
    _activities = [Activity fetchAllInContext:managedObjectContext];
    ...
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCell];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        LastWeekView* lastWeekView = [[LastWeekView alloc] initWithFrame:CGRectMake(10, 39, 120, 20)];

        lastWeekView.backgroundColor = [UIColor clearColor];

        [cell.contentView addSubview:lastWeekView];
    }

    Activity *activityToShow = [_activities objectAtIndex:[indexPath row]];
    LastWeekView *lastWeekView = (LastWeekView *)[[[cell contentView] subviews] lastObject];
    [lastWeekView setActivity:activityToShow];
    return cell;
}

请注意,您也可以将UITableViewCell子类化为使用LastWeekView替换contentView以快速访问活动属性。