【问题标题】:Different UITableViewCell for Portrait and Landscape Mode纵向和横向模式的不同 UITableViewCell
【发布时间】:2025-12-22 04:35:06
【问题描述】:

当设备处于纵向模式时,我们可以为 tableview 使用不同的 TableViewCell,而当设备变为横向模式时,我们可以使用不同的 TableViewCell 吗?

【问题讨论】:

  • 可以改用UICollectionView,在不同模式下处理垂直和水平

标签: ios swift xcode uitableview


【解决方案1】:

是的,当然。

您可以使用以下代码行来检查当前方向,然后决定在 cellForRowAtIndexPath 方法中使用哪个单元格。

if UIDevice.current.orientation == .portrait {
    //first cell
} else {
    //second cell
}

我认为您还需要一个触发点来让表格视图重新加载它的单元格。

您可以重写以下方法,然后在需要时调用 reloadData 方法。

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
}

【讨论】:

  • 它在应用启动时显示横向模式单元格,我必须将设备旋转到横向和纵向才能使纵向单元格出列。
  • var cell = UITableViewCell() if UIDevice.current.orientation == .portrait { cell = tableView.dequeueReusableCell(withIdentifier: "CustomerTableViewCell", for: indexPath) //cell.textLabel?.text = “嘿,你好宝贝”} else { cell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath) cell.textLabel?.text = "hbgusgdbdshfgdfjhdgjhmdngjsh" } return cell } 然后在 viewWillTransition 方法中重新加载单元格。
  • @ArshBhullar 关于获得正确的方向,还有其他答案。请检查一次。 *.com/questions/34452650/…
【解决方案2】:

如上,但func didRotate已被弃用,而是使用

viewWillTransition(to size: CGSize, 
               with coordinator: UIViewControllerTransitionCoordinator)

【讨论】:

    最近更新 更多