更新UITableViewCell子视图的框架不起作用

我有一个自定义(subclassed)UITableViewCell包含一些UILabels,UIButton和NSBlock作为属性。 这个子类叫做ExploreCell 。 其中两个属性是UILabels,分别命名为waitLabellastUpdateLabel

lastUpdateLabel的内容为零或为空时,即@"" ,我需要将waitLabel垂直向下(在Y轴上)移动10个像素。 我这样做是通过检查一个NSDictionary一些对象,如下面的代码所示,我已经放在-tableView:cellForRowAtIndexPath:方法中。

 CGRect frame = cell.waitLabel.frame; if ([[venue allKeys] containsObject:@"wait_times"] && ([[venue objectForKey:@"wait_times"] count] > 0)) { frame.origin.y = 43; } else { frame.origin.y = 53; } [cell.waitLabel setFrame:frame]; 

但是,此代码间歇性地工作,并试图调用-setNeedsLayout ,仍然无法正常工作。 间歇地说,我的意思是在滚动几次之后,其中一个或两个符合条件的单元格将单元格的原点向下移动10个像素,实际上它们的waitLabel的框架已经改变。

请你能告诉我为什么会发生这种情况,以及如何解决这个问题。

这看起来像是一个自动布局的问题。 如果你没有明确地closures它,那么它已经开启。 您应该对单元格的顶部(或底部)进行约束,并在代码中更改该约束的常量,而不是设置框架。 根据WWDC 2012的video,如果您使用自动布局,则不应在代码中包含任何setFrame:消息。

你试过跑步吗?

 [CATransaction flush]; [CATransaction begin]; 

在更新这些值后的主线程?

当您更改任何单元格中的布局并希望立即看到它们时,您需要使用[tableView beginUpdates] + [tableView endUpdates]。

 -(void)someMethod { [tableView beginUpdates]; // your code: CGRect frame = cell.waitLabel.frame; if ([[venue allKeys] containsObject:@"wait_times"] && ([[venue objectForKey:@"wait_times"] count] > 0)) { frame.origin.y = 43; } else { frame.origin.y = 53; } [cell.waitLabel setFrame:frame]; [tableView endUpdates]; } 

确保[tableView beginUpdates]和[tableView endUpdates]总是在一起。