Frage

I have a table view with custom cells. I'm using Xcode 5.1 and iOS 7.1. I would like to adjust a UILabel height based on the length of a string and also dynamically adjust the height of the cell to fit the label.

In

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

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

Some seem to resize correctly, others don't. As for the height of the cell, I can't get it to update based on the height of the label.

War es hilfreich?

Lösung

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

     return [self dynamicHeightAtIndexPath:indexPath]+20;

}


-(CGFloat)dynamicHeightAtIndexPath:(NSIndexPath *)indexPath
{
   CGSize maximumSize = CGSizeMake(275, 9999);
   UIFont *myFont = [UIFont fontWithName:@"MyriadPro" size:11];
   CGSize stringsize = [[self.array objectAtIndex:indexPath.row] sizeWithFont:myFont
                                                         constrainedToSize:maximumSize
                                                             lineBreakMode:NSLineBreakByWordWrapping];
   return stringsize.height;

}

Andere Tipps

The cell's height is determined solely by the value you return from tableView:heightForRowAtIndexPath:. This is a <UITableViewDelegate> method.

If you want to have the cell height be dynamic, you would need to perform a calculation in tableView:heightForRowAtIndexPath: based on the particular string that appears at that index path.

If you plan on doing a lot of scrolling, this calculation could get expensive and cause performance issues. If that is the case, I'd recommend caching the computed heights or computing them all at once and storing them in an array parallel with your data source.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top