我在 UITableViewCell 的子类中覆盖 layoutSubviews。我注意到 layoutSubviews 为每个单元格调用了两次。在第二次调用时,内容视图框架高度比第一次调用时的高度小 1:
@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
以下是控制器创建表格单元格的方式:
- (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;
}
输出:
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]
每个单元格需要 2 次通话,还是我做错了什么?