【问题标题】:iOS - drawRect: called twiceiOS - drawRect:调用了两次
【发布时间】:2014-09-03 01:07:31
【问题描述】:

我真的是 iOS 新手,我读过类似的问题,但没有一个答案有效。 我有一个表格视图,其中包含自定义单元格呈现图表(自定义UIView)和过去的足球比赛。不在同一个单元格中,但它类似于图形单元格 (BCCGraphCell) -> 对应匹配项 (BCCPastMatchCell),图形单元格 -> 对应匹配项..

我正在使用 Storyboard,并在我的自定义单元格中添加了一个图形子视图 (BCCGraphView)。网点还可以。我重写了drawRect: 方法来绘制图形,但它只被调用了两次。我在这里想念什么?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifierPastMatchCell = @"pastMatchCell";
    static NSString *cellIdentifierGraphCell = @"graphCell";
    if (indexPath.section % 2 == 0) {
        BCCGraphCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifierGraphCell];
        if (!cell) {
            cell = [[BCCGraphCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierGraphCell];
        }
        return cell;
    }
    BCCPastMatchCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifierPastMatchCell];
    if (!cell) {
        cell = [[BCCPastMatchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierPastMatchCell];
    }
    BCCMatch *matchForCell = [self.pastMatches objectForKey:self.pastMatchesKeyNames[indexPath.section]][indexPath.row];

    [self configurePastMatchCell:cell];
    return cell;
}

- (void)drawRect:(CGRect)rect
{
    self.numberOfMatches = 6; // It's suppose to affect the 6 past match cells
    CGContextRef context = UIGraphicsGetCurrentContext();
    // **** Grid thikckness and color ****
    CGContextSetLineWidth(context, [BCCUIConstant kGraphGridThickness]);
    CGContextSetStrokeColorWithColor(context, [[BCCUIConstant colorForViewGraphGrid] CGColor]);

    // Draw the Xlines
    for (int i = 0; i <= [self numberOfGridLinesX]; i++) {
        [self setNeedsDisplay];

        CGContextMoveToPoint(context, [self offsetX] + i * [self stepX], kGraphTop);
        CGContextAddLineToPoint(context, [self offsetX] + i * [self stepX], kGraphBottom);
    }
    // Draw the Ylines
    for (int i = 0; i < [self numberOfGridLinesY]; i++) {
        [self setNeedsDisplay];

        CGContextMoveToPoint(context, 0, kGraphBottom - [self offsetY] - i * [self stepY]);
        CGContextAddLineToPoint(context, kGraphWidth, kGraphBottom - [self offsetY] - i * [self stepY]);
    }

    // Commit drawing
    CGContextStrokePath(context);
}

【问题讨论】:

  • 要么使用 Outlets 要么使用 Init,如果你同时使用它会调用它 2 次,因为 Outlet 调用 initWithDecoder 方法。两者都会分别调用drawRect。

标签: ios objective-c uitableview uiview drawrect


【解决方案1】:

移除drawRect中的setNeedsDisplay

[tableView reloadData];
[self setNeedsDisplay];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2017-06-25
    • 2013-01-21
    相关资源
    最近更新 更多