简体   繁体   中英

Make UILabel Fit Height in a Dynamic Sized UITableViewCell

I have the following setup in my app: I have a UITableView which has animated height change, when a cell is selected. In the cell is I have a label, which text I want to be on one line with truncation, when the cell is not selected and then when it is selected (the cell height get's bigger) I want the text (UILabel) to be on multiple lines, based on the text.

This is my code at the moment:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {


    if(self.selectedIndex != nil && [self.selectedIndex isEqual:indexPath]) {
        return kCellHeight * 3.9;

    }

    return kCellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    ProductCell *cell = (ProductCell *) [tableView cellForRowAtIndexPath:indexPath];


    if (![indexPath isEqual:self.selectedIndex]) {

        cell.addButton.hidden = NO;

        cell.descLabel.numberOfLines = 0;
        cell.descLabel.lineBreakMode = NSLineBreakByWordWrapping;
        [cell.descLabel sizeToFit];

        tableView.scrollEnabled = NO;

        self.selectedIndex = indexPath;

    }else {

        self.selectedIndex = nil;

        cell.descLabel.lineBreakMode = NSLineBreakByTruncatingTail;

        tableView.scrollEnabled = YES;


        cell.addButton.hidden = YES;

    }






    [tableView beginUpdates];


    [tableView endUpdates];


}

The first part (when the cell is selected, expanded and the height gets bigger) the text fits as I want, but the second part (when the cell is contracted, and the cell height get back to the normal height) the text does not fit to the new height and is truncated as I want it to, it just stays multi lined. How can I fix this? So when the cell is selected the text gets multilined and when the cell is deselected the text gets back to its normal truncated state?

EDIT:

Override - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

and add below line in this function cell.descLabel.numberOfLines = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM