第二次轮换后,tableView.tableHeaderView中的视图帧错误

时间:2017-02-13 15:52:44

标签: ios swift uitableview rotation uitraitcollection

我想根据大小类构建一个简单的Swift 3 iOS 10应用程序,它有两种不同的布局。当我的viewController的{​​{1}}类型为traitCollection.verticalSizeClass时,我希望我的.regularblueView的子类)成为UIView的{​​{1}}高度为tableView.tableHeaderView。当我的50 viewController类型为traitCollection.verticalSizeClass时,我希望我的.compact位于左侧(自动布局宽度约束为blueView)并且我的240位于右侧。

这是我的tableView实例的代码:

UIViewController

以下屏幕截图显示了以纵向模式设置场景的故事板:

enter image description here

以下屏幕截图显示了以横向模式设置场景的故事板:

enter image description here

可在此Github repo上找到完整的项目。

启动时一切正常:import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! { didSet { tableView.dataSource = self tableView.delegate = self } } @IBOutlet weak var blueView: UIView! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if self.traitCollection.verticalSizeClass == .regular { blueView.bounds = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.bounds.width, height: 50) tableView.tableHeaderView = blueView } else { self.tableView.tableHeaderView = nil } } } 设置为blueView且高度为tableView.tableHeaderView。如果我旋转设备,一切仍然正常:50blueView有正确的约束。

但是,如果我再次旋转设备,tableView将从控制器的视图中消失,blueView会显示空的tableView。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

错误的自动布局限制导致了我的问题。我设法通过删除blueView的{​​{1}}并在每次轮播时切换constraints的{​​{1}}属性来解决此问题。

虽然我怀疑这是解决此问题的最佳方法,但以下代码可以正常工作并且不会生成自动布局约束错误日志。

blueView