如何从 1 开始向每个 tableview 行添加数字
How do I add numbers to each tableview row beginning from 1
我创建了一个带有 Prototype Cell 的 TableView,里面有很多内容、多个标签、2 张图片和一个视图,如果该行被选中,该视图是彩色的。
我现在想做的是,我想为创建的每一行添加一个数字,以便用户可以看到有多少行。我不能使用从数据库中获得的 ID,因为它是字符的随机组合。
我添加了一个 Int 变量 'participantID',它从 1 开始,随着创建的每个单元格递增 1,并将值写入原型单元格内的标签中。
这正是我想要的,只有一个问题:每次我在 table 中滚动时,ID 都会递增。我知道这是因为细胞的重复使用,但是我找不到解决这个问题的方法。
这是它的样子 (particID):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tbcCourseParticipant", for: indexPath) as! participantCell
let partic = participants[indexPath.row]
cell.lblId?.text = String(particID)
cell.lblName?.text = partic.name
cell.lblFirstName?.text = partic.firstName
cell.lblBirthDate?.text = partic.birthDate
cell.lblPhoneNr?.text = partic.phoneNr
cell.lblPrice?.text = String(partic.payed) + "€"
particID += 1
return(cell)
}
总行数为participants.count
。 this 行的数量是 indexPath.row+1
(我加 1 是因为用户不会像程序员那样期望从零开始计数)。
所以我会说:
cell.lblId?.text = String(indexPath.row+1)
或者也许:
cell.lblId?.text = String(indexPath.row+1) + " of " + String(participants.count)
我创建了一个带有 Prototype Cell 的 TableView,里面有很多内容、多个标签、2 张图片和一个视图,如果该行被选中,该视图是彩色的。
我现在想做的是,我想为创建的每一行添加一个数字,以便用户可以看到有多少行。我不能使用从数据库中获得的 ID,因为它是字符的随机组合。
我添加了一个 Int 变量 'participantID',它从 1 开始,随着创建的每个单元格递增 1,并将值写入原型单元格内的标签中。
这正是我想要的,只有一个问题:每次我在 table 中滚动时,ID 都会递增。我知道这是因为细胞的重复使用,但是我找不到解决这个问题的方法。
这是它的样子 (particID):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tbcCourseParticipant", for: indexPath) as! participantCell
let partic = participants[indexPath.row]
cell.lblId?.text = String(particID)
cell.lblName?.text = partic.name
cell.lblFirstName?.text = partic.firstName
cell.lblBirthDate?.text = partic.birthDate
cell.lblPhoneNr?.text = partic.phoneNr
cell.lblPrice?.text = String(partic.payed) + "€"
particID += 1
return(cell)
}
总行数为participants.count
。 this 行的数量是 indexPath.row+1
(我加 1 是因为用户不会像程序员那样期望从零开始计数)。
所以我会说:
cell.lblId?.text = String(indexPath.row+1)
或者也许:
cell.lblId?.text = String(indexPath.row+1) + " of " + String(participants.count)