gpt4 book ai didi

ios - Swift:UITableViewCell 行高

转载 作者:行者123 更新时间:2023-11-28 09:35:49 25 4
gpt4 key购买 nike

我要问的问题已经问了很多,但不是我想要的。

这很简单,我想更改特定单元格的行高,我想在 UITableViewCell 类本身中执行此操作。我试图从我的 UIViewController 调用 TableView :

ViewController().tableView.rowHeight = 100

但是我得到一个错误。所以我的问题是,是否可以更改 tableviewcell 类本身的行高?如果是,怎么办?

谢谢!

最佳答案

更新:对Comment的回应

以一个标志开始,以跟踪单元格是否应该展开:

let cellShouldExpand = false

当你想为高度的变化设置动画时调用以下方法:

cellShouldExpand = true
tableView.beginUpdates()
tableView.endUpdates()

并将heightForRowAt:修改如下:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == indexPathOfCellYouWantToChange && cellShouldExpand {
return 100 // the height you want
} else {
return UITableViewAutomaticDimension
}
}

执行相反的操作以恢复更改(即设置 cellShouldExpand = false 并再次调用 tableview 更新函数)。

原始回复

如果您希望所有单元格具有相同的高度,那么您可以更改 rowHeight,但正确的方法不是通过执行 ViewController()... 因为它实例化了一个新的 View Controller 。相反,您可以像这样简单地自动引用 TableView :

tableView.rowHeight = 100

self.tableView.rowHeight = 100

如果您想为特定单元格设置不同的行高,您需要使用 UITableViewDelegate。在文件顶部声明 View Controller 时添加委托(delegate)一致性:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

然后在 ViewController 类中,您可以实现以下方法:

let indexPathOfCellYouWantToChange = IndexPath(row: 2, section: 0)

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == indexPathOfCellYouWantToChange {
return 100 // the height you want
} else {
return UITableViewAutomaticDimension
}
}

(indexPathOfCellYouWantToChange 应设置为您有兴趣更改其高度的单元格的行和部分)

Apple 文档提供了有关如何正确使用此方法的更多信息: https://developer.apple.com/reference/uikit/uitableviewdelegate/1614998-tableview

Discussion

The method allows the delegate to specify rows with varying heights. If this method is implemented, the value it returns overrides the value specified for the rowHeight property of UITableView for the given row. There are performance implications to using tableView(_:heightForRowAt:) instead of the rowHeight property. Every time a table view is displayed, it calls tableView(_:heightForRowAt:) on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more). See also tableView(_:estimatedHeightForRowAt:).

关于ios - Swift:UITableViewCell 行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43478160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com