Search code examples
objective-cuitableviewuiviewdidselectrowatindexpath

Add subview to UITableViewCell on selection


I'm trying to add a UIView that is supposed to strikethrough the text (don't worry about the horizontal misplacement).

However, when selecting a row, the line is added several rows below. Why?

Strange selection behaviour

Here's my code:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@", indexPath);

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UILabel *label = cell.textLabel;

    CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}];
    CGFloat strikeWidth = textSize.width;

    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(self.view.bounds.size.height / 2, 200, strikeWidth, 2)];
    lineView.backgroundColor = [UIColor redColor];

    lineView.tag = 100;

    [cell.contentView addSubview:lineView];
}

Solution

  • Instead of using a UIView and adding a subview to the cell, you should use an NSAttributedString for the cell text and the NSStrikethroughStyleAttributeName to strike through with an NSStrikethroughColorAttributeName for the strikethrough colour.