Reza_Rg
Reza_Rg

Reputation: 3374

How to show full text of a labelview in cell, when height is changed

I have a tableview with a customized cell in it, in my cell, I have one label and one image, text in label is long, so I just show first 2 lines and then show 3dots "..." using linebreaks, and then when user tap cell, it will expand to show full text of label I change height of cell when taped, I do this like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{       
if ([tableView indexPathsForSelectedRows].count) {

    if ([[tableView indexPathsForSelectedRows] indexOfObject:indexPath] != NSNotFound) {


        MsgInfo *info = [_msgInfos objectAtIndex:indexPath.row];
        NSString *displayString = info.msg;




        CGRect boundingRect =
        [displayString boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width - 2 * 10, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:
            @{ NSFontAttributeName : [UIFont fontWithName:@"B Yekan" size:18.0f]} context:nil];

        CGFloat rowHeight = ceilf(boundingRect.size.height);

        NSLog(@"Height = %f for '%@'", rowHeight, displayString);

        return 54 + rowHeight + 2 * 10; // Expanded height


    }

    return 92; // Normal height
}

return 92; // Normal height
}

So when I tap a cell, it expands based on my label text font and size,

But now I want to show full text of label, I know I have to set label.numberofline =0 in didSelectRowAtIndexPath, but it doesnot work.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"MsgCell";

UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                  reuseIdentifier:CellIdentifier];
}


UILabel *nameLabel = (UILabel *)[cell viewWithTag:100];

nameLabel.numberOfLines =0;
[nameLabel sizeToFit];
[nameLabel setLineBreakMode:NSLineBreakByWordWrapping];

    [self.tableView beginUpdates];
[self.tableView endUpdates];
}

any help?

Upvotes: 0

Views: 467

Answers (1)

Wain
Wain

Reputation: 119031

In didSelectRowAtIndexPath you're creating a new cell and changing its settings (not editing the existing cell and not any cell that will be used for display soon). What you should be doing is triggering a reload of the selected cell so that the new height is recalculated and the cell reloaded. In tableView:cellForRowAtIndexPath: you should have similar logic to check if the row is selected and then set the number of lines on the label.

Doing it in tableView:cellForRowAtIndexPath: will also prevent you from having issues on deselection as you must always set the number of lines for each cell whenever it is reused.

Upvotes: 1

Related Questions