表视图布局在设备方向更改时未更新

时间:2019-06-07 17:31:21

标签: swift uitableview screen-rotation

因此,我创建了一个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")

    }
}

这就是我在模拟器中得到的。在横向模式下,表格视图仅是视图宽度的一半,而它应该始终占据整个屏幕。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

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

您可以尝试将其设置为true,也可以尝试将表约束为这样的视图:

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。就个人而言,我更喜欢这种方法,而不是依赖于视图的框架。