在 Swift 中动态更改 TableView 单元格高度

iosmobile developmentiphone/ipadswift更新于 2026/1/19 8:52:17

要在 iOS 中动态更改 TableView 单元格的高度,即根据可用内容调整单元格大小,我们需要使用自动尺寸属性。我们将通过一个示例项目来演示。

创建一个空项目,并转到其 viewController 类,使其符合 UITableViewDataSource 和 UITableViewDelegate 接口。

现在,在下面的代码中,我们将首先创建一个表格,然后为该表格注册一个单元格,并添加一些表格属性。

我们将设置表格视图委托和表格视图数据源。

最后,我们将表格视图添加到视图中。然后我们将在视图控制器的 viewDidLoad 方法中调用此函数。

注意:我们设置了一个名为estimatedRowHeight 的属性 

func initTableView() {
   let tableView = UITableView()
   tableView.frame = self.view.frame
   tableView.dataSource = self
   tableView.delegate = self
   tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
   tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
   tableView.estimatedRowHeight = UITableView.automaticDimension
   self.view.addSubview(tableView)
}

现在,这段代码会将表格添加到我们的视图中,我们还需要告诉表格我们需要多少个部分和多少行。

func numberOfSections(in tableView: UITableView) -> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 5
}
func numberOfSections(in tableView: UITableView) -> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 5

这段代码会在表格视图的第二行创建一行较大的文本,以便根据内容大小自动调整高度。

注意: UITableViewCell 默认有一个 label 属性,而一个标签默认只有一行长度,因此我们需要修改它才能看到自动调整尺寸的功能。

现在我们需要告诉表格其单元格的高度。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return UITableView.automaticDimension
}

运行上述代码,我们得到以下结果。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部