需要有关在 UITableViewCell 上显示自定义分隔符的帮助

Need assistance regarding displaying custom separator on UITableViewCell

我试图在 UITableViewCell 上有条件地绘制一个分隔符,所以首先我设置了 [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone]; 然后在我的 UITableViewCell 子类中我做了这个

.h 文件

@property BOOL separator;

.m 文件

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    if(self.separator)
        CGContextSetStrokeColorWithColor(context, [[UIColor colorWithRed:188.0/255.0 green:186.0/255.0 blue:193.0/255.0 alpha:1.0] CGColor]);
    else
        CGContextSetStrokeColorWithColor(context, [[UIColor clearColor] CGColor]);
    CGContextSetLineWidth(context, 0.5);
    CGContextMoveToPoint(context, 55.0, self.bounds.size.height);
    CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height);
    CGContextDrawPath(context, kCGPathStroke);
}

cellForRowAtIndexPath 方法中我正在这样做

        if(indexPath.section == 0) {
                if(indexPath.row == 0) {
                    cell1 = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
                    cell1.lbl1.text = name;
                    cell1.lbl1.font = [UIFont fontWithName:@"Helvetica-Bold" size:17.0];
                    cell1.separator = YES;
                }
        }

// other cells with different identifiers...

        if(indexPath.section == 5) {
            cell1 = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
            cell1.lbl1.text = @"March 25";
            cell1.lbl1.font = [UIFont fontWithName:@"Helvetica-Regular" size:1.0];
            cell1.separator = NO;
            return cell1;
        }

在第 5 节中,我不想显示分隔符,所以我做了 cell1.separator = NO; 但为什么我仍然得到它?

它可能会被重新绘制,因为 table 单元格是可重复使用的。如果分隔符 属性 为假,请尝试将其删除。

您的 drawRect: 方法可能在单元格出队后未在单元格对象上调用。您可以尝试为 separator 属性 添加一个 setter 并在其中调用 setNeedsDisplay,如下所示:

- (void)setSeparator:(BOOL)separator
{
    _separator = separator;
    [self setNeedsDisplay];
}

这将导致在为 separator 属性.

分配新值后调用您的 drawRect: 方法