【问题标题】:Table View layout not updating on device orientation change表视图布局未在设备方向更改时更新
【发布时间】: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


【解决方案1】:

通常,如果您希望视图的框架确定其锚点,则不要设置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。就个人而言,我更喜欢这种方法而不是依赖视图的框架。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-10
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多