我正在尝试在 TableView 中构建两个(或更多)自定义单元格,并且每个单元格都没有自定义类,我正在使用 Storyboard 来进行单元格原型(prototype)设计和 tableView.dequeueReusableCell(withIdentifier: "customCellName", for: indexPath)
创建与 cellForRowAt
不同的单元格方法。
我需要单元类型 1 的高度与单元类型 2 不同,但如果尝试使用 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
单元格类型 2 显示不正确。
我尝试构建一个“虚拟项目”来理解正确的方法,这里是我的代码:
var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let value = dataArray[indexPath.row]
if (value == "second") || (value == "Hawaii") {
cell = self.tableView.dequeueReusableCell(withIdentifier: "cellTwo", for: indexPath)
}
let lbl = cell.viewWithTag(100) as! UILabel
lbl.text = dataArray[indexPath.row]
return cell
在 ViewDidLoad 中:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.estimatedRowHeight = 200
}
这是结果:
每个大小相同的单元格都不适合我。
最佳答案
如果您想创建自定义单元格外观,则必须创建 UITableViewCell
的子类 - 有一些 great tutorials on how to do that .
然后,您必须注册自定义单元格,以便您的 UITableView
知道它。请参阅register(_:forCellReuseIdentifier:)
方法。
在您的 tableView(_:heightForRowAt:)
中您可以编写以下代码来计算特定单元格的高度:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
let value = dataArray[indexPath.row]
if (value == "second") || (value == "Hawaii") {
return 180.0
} else {
return 40.0
}
}
关于ios - 无法将超过一两个单元格放入不同大小的 UITableView Swift 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867758/