Table 视图布局不会随着设备方向的变化而更新

Table View layout not updating on device orientation change

所以我创建了一个 tableView 并使它的框架与视图的框架相同,因此它应该与 phone 屏幕的大小相同。但是,当我在模拟器中将设备方向更改为横向时,table 视图与纵向模式保持相同的尺寸。

这是我的table查看代码:

        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")

    }
}

这是我在模拟器中得到的。在横向模式下,table 视图只有视图宽度的一半,但它应该始终填满整个屏幕。

通常,如果您希望视图的框架确定其锚点,则无需设置 tableView.translatesAutoresizingMaskIntoConstraints = false。将该标志设置为 false 将强制它依赖锚而不是它自己的视图框架来设置其约束。

您可以尝试将其设置为 true,或者您可以尝试将 table 限制为视图,如下所示:

self.view.addSubview(tableView)
tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

这会将其限制在视图框架内。如果你这样做,你就不需要担心设置tableView.frame = view.frame。就个人而言,我更喜欢这种方法而不是依赖视图的框架。