Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

layoutSubviews called twice on UITableViewCell

Tags:

ios

I'm overriding layoutSubviews in my subclass of UITableViewCell. I noticed that layoutSubviews is called twice for each cell. On the second call, the content view frame height is 1 less than the height on the first call:

@implementation MyUITableViewCellCell

+ (NSString *)asString:(CGRect) rect {
     NSString *res = [[NSString alloc] initWithFormat:@"[%f %f %f %f]",
                 rect.origin.x, rect.origin.y, rect.size.width, rect.size.height];
     [res autorelease];
     return res;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    NSLog(@"Here I am %@ frame=%@ cvframe=%@,
      self.text, 
      [MyUITableViewCellCell asString:self.frame],
      [MyUITableViewCellCell asString:self.contentView.frame]);
}

@end

Here's how the controller creates the table cells:

- (NSString*)dataAtIndex:(NSInteger)index
{
    NSString* data = [[NSString alloc] initWithFormat:@"Row %d", index];
    return [data autorelease];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath     *)indexPath
{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Alex";

    NSInteger index = [indexPath row];
    MyUITableViewCellCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[MyUITableViewCellCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.text = [self dataAtIndex:index];
    return cell;
}

Output:

Here I am Row 0 frame=[0.000000 0.000000 320.000000 30.000000] cvframe=[0.000000 0.000000 320.000000 30.000000]
Here I am Row 1 frame=[0.000000 30.000000 320.000000 30.000000] cvframe=[0.000000 0.000000 320.000000 30.000000]
Here I am Row 0 frame=[0.000000 0.000000 320.000000 30.000000] cvframe=[0.000000 0.000000 320.000000 29.000000]
Here I am Row 1 frame=[0.000000 30.000000 320.000000 30.000000] cvframe=[0.000000 0.000000 320.000000 29.000000]

Are 2 call per cell expected, or am I doing something wrong?

like image 260
agherardi Avatar asked Jul 18 '12 17:07

agherardi


1 Answers

My guess is that UITableView resizes the height of the cell by one pixel to make room for drawing dividing lines. Your layoutSubviews method is getting called again after UITableView sets the new frame for the cell.

like image 95
rsswtmr Avatar answered Oct 18 '22 03:10

rsswtmr