手动填写UITableView单元格标签



我正在尝试填充UITableView单元格的标签。

我的问题是它只是填满了第一个单元格。这是我到目前为止得到的(应该填充三个单元格,但只有第一个是(

import UIKit
class StatsViewController: UITableViewController {

var vc = ViewController()

override func viewDidLoad() {
super.viewDidLoad()
// tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// tableView.reloadData()
//tableView.delegate = self

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) //ACHTUNG: "ListItem" ist der Name meiner Zelle
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath)
let cell3 = tableView.dequeueReusableCell(withIdentifier: "cell3", for: indexPath)
let cell4 = tableView.dequeueReusableCell(withIdentifier: "cell4", for: indexPath)
let cell5 = tableView.dequeueReusableCell(withIdentifier: "cell5", for: indexPath)

if let label = cell.viewWithTag(1000) as? UILabel {
if indexPath.row == 0{
label.text = "*** Quittung ***"
//label.font = UIFont(name: label.font.fontName, size: 20)
}
}
if let label2 = cell2.viewWithTag(1001) as? UILabel {
if indexPath.row == 1{
label2.text = "------------------"
}
}
if let label3 = cell3.viewWithTag(1002) as? UILabel {
if indexPath.row == 2{
label3.text = "*SAEULENNR. 2 " + String( vc.preisProLiter) + "EUR/Liter*"
}
}

return cell
}
}

正如你所看到的:我想手动填充5个单元格。

而第一个细胞具有识别器"1";单元格";并且第一小区的标签具有Tag=1000。

第二个单元具有标识符";cell2";并且第二小区的标签具有Tag=1001。等等…

这是一张现在的截图:

屏幕截图

谢谢你的帮助!

如果将相同的indexPath分配给一组单元格,iOS将覆盖所有单元格,并将给定的identifier绑定到单元格,然后填充它。

这样做

if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
//.
//.
//.
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath)
//.
//.
//.
return cell
} else if others 
//.
//.
//.
//.
} else {
return UItableViewCell()
}

此外,你可以通过将细胞浇铸到类型来对其进行一点优化

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TheTypeOfTheCell
cell.yourLabel.text = "*** Quittung ***"
//.
//.
//.
return cell

最新更新