为什么self.frame和self.contentView.frame经常因UITableViewCell而不同?

use*_*951 6 objective-c xcode4.5

我洒了

NSAssert(abs(self.frame.size.height-self.contentView.frame.size.height)<=1,@"Should be the same");
Run Code Online (Sandbox Code Playgroud)

在创建UITableViewCell返回时的各个地方.

结果往往不同.有时候是1像素,有时是2.

我想知道问题是什么?在cellForRowAtIndexPath中有什么东西让它们与众不同吗?

他们的开始是一样的.没有编辑等

看看这个简单的snipet

BGDetailTableViewCell * cell= (BGDetailTableViewCell*)[tableView dequeueReusableCellWithIdentifier:[BGDetailTableViewCell reuseIdentifier]];

if (cell==nil)
{
    cell = [[BGDetailTableViewCell alloc]init];
}
else
{
    NSAssert(abs(cell.frame.size.height-cell.contentView.frame.size.height)<=1,@"Should be the same"); //Sometimes this fail
}

NSOrderedSet *Reviews = [self.businessDetailed mutableOrderedSetValueForKey:footer.relationshipKey];
Review * theReview = [Reviews objectAtIndex:row];
cell.theReview = theReview;
NSAssert(abs(cell.frame.size.height-cell.contentView.frame.size.height)<=1,@"Should be the same");//This one never fail right before returning cell
return cell;



`NSAssert(abs(cell.frame.size.height-cell.contentView.frame.size.height)<=1,@"Should be the same")`; never fails right before returning the cell.
Run Code Online (Sandbox Code Playgroud)

然而,在我有时将细胞出列后,它失败了.

这是结果

(lldb) po cell
$0 = 0x0c0f0ae0 <BGDetailTableViewCell: 0xc0f0ae0; baseClass = UITableViewCell; frame = (0 424; 320 91); hidden = YES; autoresize = W; userInteractionEnabled = NO; layer = <CALayer: 0xc01e800>>
(lldb) po cell.contentView
$1 = 0x0c086080 <UITableViewCellContentView: 0xc086080; frame = (10 1; 300 89); gestureRecognizers = <NSArray: 0xc0c7ee0>; layer = <CALayer: 0xc0ebbf0>>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,tableView处于分组模式.我认为这与它有关.

Mar*_*ark 5

这两个矩形位于不同的坐标系中,不一定匹配。

cell.frame指的是单元格在其父视图坐标系 ( cell.superview) 中的矩形。单元格的超级视图是 UITableView。单元格的框架将由表视图操纵,以便正确布局。这还包括修改高度以匹配其rowHeight属性或委托方法返回的值tableView:heightForRowAtIndexPath:

细胞contentView的“内部”是细胞的“内部”。它的超级视图是单元格本身,它的子视图有自己的局部坐标系。这些不是由 tableView 操纵的,而是由单元格(例如单元格子类)本身对其设置的约束进行操纵。您的子类可以实现layoutSubviews以按照contentView您想要的方式调整大小。

如果您想确保您的 contentView 与单元格的高度(和边界)匹配,请在您的UITableViewCell子类中实现layoutSubviews如下:

-(void)layoutSubviews
{
    self.contentView.frame = self.bounds;
}
Run Code Online (Sandbox Code Playgroud)

您可以对contentView所需的框架进行任何修改,但请注意这些修改应该使用超级视图bounds而不是frame.