在 UITableViewCell 中,您不能直接更改 textLabel 的文本,因为它是只读的。相反,您应该在 UITableViewCell 的子类中覆盖 prepareForReuse()
方法,并在此方法中设置 textLabel 的文本。
以下是如何在 UITableViewCell 子类中更改 textLabel 文本的示例:
CustomTableViewCell
的子类。import UIKit
class CustomTableViewCell: UITableViewCell {
}
protocol CustomTableViewCellDelegate: AnyObject {
func updateTextLabelText(for cell: CustomTableViewCell, withText text: String)
}
CustomTableViewCell
类中添加一个代理属性。weak var delegate: CustomTableViewCellDelegate?
func setTextLabelText(_ text: String) {
self.textLabel?.text = text
delegate?.updateTextLabelText(for: self, withText: text)
}
updateTextLabelText(for:withText:)
方法以更新cell的textLabel。extension ViewController: CustomTableViewCellDelegate {
func updateTextLabelText(for cell: CustomTableViewCell, withText text: String) {
// 更新 cell 的 textLabel 文本
cell.textLabel?.text = text
}
}
tableView(_:cellForRowAt:)
方法中,将代理设置为 ViewController 实例,并调用 setTextLabelText(_:)
方法更新 textLabel。func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
cell.delegate = self
cell.setTextLabelText("Your text goes here")
return cell
}
这样,在 cell 被重用时,prepareForReuse()
方法将会被调用,更新 textLabel 的文本。如果需要为不同单元格设置不同的文本,可以在 setTextLabelText(_:)
方法中根据 indexPath 或其他条件设置不同的文本。
领取专属 10元无门槛券
手把手带您无忧上云