DrawRect完成和UI刷新之间的时间差

时间:2012-07-18 10:46:29

标签: ios drawrect lag

我有一个使用开源类MMGridView的iPad应用程序。 基本上我执行CoreData查询,然后此类以网格模式在屏幕上绘制框以表示结果。这些盒子包括照片。 一切都很好,除了有时在屏幕上绘制UI之前有一个无法解释的时间延迟。有时刷新是即时的,有时超过20秒。它的行为似乎非常随机。

我已经设法确定:

  • 每次调用DrawRect。
  • 在DrawRect方法中没有出现延迟。
  • 当我运行时间分析器时,从我所知道的,在这段时间内没有发生任何事情

我的问题是,在调用DrawRect之后会发生什么,我可以尝试查看以确定问题?

绝对不会有任何想法。

另请注意,用户交互能够缩短延迟时间。 - 旋转iPad(触发重绘)总是让ui立即刷新 - 按下按钮重做相同的查询通常会刷新屏幕

所以看起来真的有一些随机的延迟,而不是任何处理器/工作负载问题。问题是以编程方式,我无法判断UI是否已更新。否则我可以要求它再次重绘。

我包含了DrawRect方法中的代码,以防万一引发任何想法,但从我所知道的,这个方法在滞后发生之前完成。

- (void)drawRect:(CGRect)rect {

if (self.dataSource && self.numberOfRows > 0 && self.numberOfColumns > 0) {
    NSInteger noOfCols = self.numberOfColumns;
    NSInteger noOfRows = self.numberOfRows;
    NSUInteger cellsPerPage = noOfCols * noOfRows;
    NSLog(@"rows = %d, cols = %d", noOfCols, noOfRows);
    CGRect gridBounds = self.scrollView.bounds;
    CGRect cellBounds = CGRectMake(0, 0, gridBounds.size.width / (float)noOfCols, 
                                   gridBounds.size.height / (float)noOfRows);

    CGSize contentSize = CGSizeMake(self.numberOfPages * gridBounds.size.width, gridBounds.size.height);
    [self.scrollView setContentSize:contentSize];

    for (UIView *v in self.scrollView.subviews) {
        [v removeFromSuperview];
    }

    for (NSInteger i = 0; i < [self.dataSource numberOfCellsInGridView:self]; i++) {
        MMGridViewCell *cell = [self.dataSource gridView:self cellAtIndex:i];
        [cell performSelector:@selector(setGridView:) withObject:self];
        [cell performSelector:@selector(setIndex:) withObject:[NSNumber numberWithInt:i]];

        NSInteger page = (int)floor((float)i / (float)cellsPerPage);
        NSInteger row  = (int)floor((float)i / (float)noOfCols) - (page * noOfRows);

        CGPoint origin = CGPointMake((page * gridBounds.size.width) + ((i % noOfCols) * cellBounds.size.width), 
                                     (row * cellBounds.size.height));

        CGRect f = CGRectMake(origin.x, origin.y, cellBounds.size.width, cellBounds.size.height);
        cell.frame = CGRectInset(f, self.cellMargin, self.cellMargin);

        [self.scrollView addSubview:cell];
    }
}
}

1 个答案:

答案 0 :(得分:1)

好的问题解决了,因为有一个非常清晰简洁的描述何时使用以及何时不使用drawRect:由Peter Hosey回答这个问题。 What is the proper way to make it so core graphics does not lag?

基本上,这是我正在使用的开源类MMGridView中的一个错误,因为它不应该使用drawRect:来设置UIScrollView上的框或单元格。这是因为没有实际绘图。

因此,通过更改上述方法的名称并直接在我之前调用setNeedsDisplay的位置调用它,不再存在任何随机延迟。