【发布时间】:2019-06-07 17:31:21
【问题描述】:
所以我创建了一个 tableView 并使它的框架与视图的框架相同,因此它应该与手机屏幕的大小相同。但是,当我在模拟器中将设备方向更改为横向时,表格视图与纵向模式保持相同的尺寸。
这是我的 tableView 代码:
func setTableView() {
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.frame = view.frame
tableView.backgroundColor = UIColor.lightGray
tableView.delegate = self
tableView.dataSource = self
tableView.separatorColor = UIColor.lightGray
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
这里是 viewDidLoad 方法:
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
setTableView()
}
这是我检测方向变化的方法:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else {
print("Portrait")
}
}
这是我在模拟器中得到的。在横向模式下,表格视图只有视图宽度的一半,而它应该始终填满整个屏幕。
【问题讨论】:
-
如果您使用此方法,您需要确保在设备旋转时重新绘制框架。你的
viewWillTransition(to:)方法是打到print("Landscape")还是print("Portrait")? -
确保将 tableView 的所有边缘都约束到它的 superView。
标签: swift uitableview screen-rotation