方向更改后,UITableView布局中的错误

我有一个基于自动布局(约束)的应用程序,并注意到在方向更改后,tableview存在问题。 repro的步骤如下(我有一个非常基本的repro应用程序 – 一个tableview和添加一个新的项目添加button)。

  1. 将您的应用程序旋转到横向模式,以便tableview现在是横向的。
  2. 添加一个项目到tableview看下面的1
  3. 旋转回肖像,tableview现在将在水平平移上浮动(就像滚动查看器的内容大小是风景),参见[2]

1代码添加

- (IBAction)onAdd:(id)sender { count ++; [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom]; } 

[2]浮动表视图

在这里输入图像说明

任何想法如何解决这个问题? 另外,如何知道这是已知问题还是我应该向苹果公司报告?

我认为这是一个错误; 如果您将该项目从自动布局中转换出来并设置适当的resize掩码,则一切正常。 你应该提交一个bug,特别是因为你有一个简单的示例项目,很好地重现它。

你的情况正如你所猜测的 – 即使视图本身被调整为肖像,滚动视图的内容视图仍然保留在横向宽度,所以你突然间可以水平拖动。

幸运的是有相当简单的解决方法。 我尝试了setNeedsLayoutsetNeedsUpdateConstraints各种组合,但没有成功,但可以实现以下两种解决scheme之一:

 -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [self.tableView beginUpdates]; [self.tableView endUpdates]; } 

要么,

 -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { CGSize contentSize = self.tableView.contentSize; contentSize.width = self.tableView.bounds.size.width; self.tableView.contentSize = contentSize; } 

我发现上面的答案大部分时间都在工作,但不是全部时间。 最健壮的解决scheme是UITableView的子类,并在layoutSubviews中设置contentSize:

 - (void)layoutSubviews { [super layoutSubviews]; CGSize contentSize = self.contentSize; contentSize.width = self.bounds.size.width; self.contentSize = contentSize; }