我想根据大小类构建一个具有两种不同布局的简单 Swift 3 iOS 10 应用程序。当我viewController的traitCollection.verticalSizeClass类型为 时.regular,我希望我的blueView(的子类 UIView)tableView.tableHeaderView的高度为50。当我viewController的traitCollection.verticalSizeClass类型为 时.compact,我希望我blueView在左边(自动布局宽度约束为240)并且我tableView在右边。
这是我的UIViewController实例的代码:
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
}
}
}
以下屏幕截图显示了场景设置为纵向模式的情节提要:
以下屏幕截图显示了场景设置为横向模式的情节提要:
完整的项目可以在这个Github repo上找到。
启动时一切正常:blueView设置为tableView.tableHeaderView并且具有正确的高度50。如果我旋转我的设备,一切仍然正常:blueView并且tableView有正确的约束。
但是,如果我第二次旋转设备,blueView就会从控制器的视图中消失,并且tableView显示一个空的tableHeaderView. 我能做些什么来解决这个问题?

