Question

I'm trying to have a label in a UITableViewCell that can span two lines, but if there is only one line align it vertically to the first line.

The code to work out the label height (below) seems to work, but the label isn't getting relaid/repainted. If I scroll the cell off the view and back again, the label has the correct height.

I have tried [cell setNeedsLayout], [cell setNeedsDisplay], [titleLabel setNeedsLayout] and [titleLabel setNeedsLayout, and no combination has worked.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ItemCell" forIndexPath:indexPath];

    Item *item = (self.items)[indexPath.section][indexPath.row];

    UILabel *titleLabel = (UILabel *)[cell viewWithTag:100];
    titleLabel.text = item.title;
    titleLabel.backgroundColor = [UIColor redColor];

    // Some titles span two lines, so resize to fit the new content.

    CGRect textRect = [titleLabel.attributedText boundingRectWithSize:CGSizeMake(titleLabel.frame.size.width, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];
    CGRect labelRect = CGRectIntegral(CGRectMake(titleLabel.frame.origin.x,
                                             titleLabel.frame.origin.y,
                                             titleLabel.frame.size.width,
                                             textRect.size.height));
    NSLog(@"%@, %f", titleLabel.text, labelRect.size.height); // This logs out the correct height

    titleLabel.frame = labelRect;

    return cell;
}
Was it helpful?

Solution 2

Turns out I'm using auto layout, which means I can't set the frame directly. Instead I need to add a height constraint and connect it to an IBOutlet on my UITableViewCell subclass.

OTHER TIPS

please try my suggestion. may be it will help you with the reusability of cell in UITableview. Please Check the following points in you code:

  1. What to do if you cell == nil while redrawing UITableView in iPhone. thats why you have to make condition like below for reusability of UITableViewCell.

    // Get table View Cell
    static NSString *CellIdentifier = @"ItemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    
    if (cell == nil) {
    
        NSArray *nib;
        nib = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
        cell = (UITableViewCell *) [nib objectAtIndex:0];
    }
    

Please test it and let me know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top