我正在尝试研究如何编辑已添加到 UITableView 单元格中的 subview 的标签。这是代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var cellTitleLabel = UILabel(frame: CGRect(x: 45,y: 2,width: 100,height: 20))
cellTitleLabel.textAlignment = NSTextAlignment.left
cellTitleLabel.text = "Title"
cellTitleLabel.font = UIFont(name: "Swiss721BT-Roman", size: 16)
cell.addSubview(cellTitleLabel)
return cell
}
现在我希望能够将字符串从“标题”更改为任何内容,但似乎我可以更新该文本的唯一方法是删除 subview ,然后添加一个具有更新参数的新 subview 。是不是不可能做这样的事情:
cell.cellTitleLabel.text = "New Title"
谢谢,任何帮助将不胜感激!
最佳答案
我看到的问题是,当您加载单元格时,您正在创建一个 UILabel
作为单元格的 subview ,但您没有保留对该标签的任何引用。因此,单元格在初始化后不再具有任何名为 cellTitleLabel
的属性。
我建议创建一个自定义的 UITableViewCell
子类,如下所示:
import UIKit
class CustomTableViewCell: UITableViewCell {
var cellTitleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization Code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setCellContent(text: String) {
let cellTitleLabel = UILabel(frame: CGRect(x: 45,y: 2,width: 100,height: 20))
cellTitleLabel.textAlignment = NSTextAlignment.left
cellTitleLabel.text = text
cellTitleLabel.font = UIFont(name: "Swiss721BT-Roman", size: 16)
self.addSubview(cellTitleLabel)
self.cellTitleLabel = cellTitleLabel
}
}
然后当您设置调用cellForRowAtIndexPath
时,您可以实例化自定义单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
cell.setCellContent(text: "Cell Title")
return cell
}
然后你会有一个充满 CustomTableViewCell
子类的表格,因为它是单元格,每个单元格都有一个名为 cellTitleLabel
的 UILabel
属性,你可以根据需要更改。
编辑: - 我忘记添加您使用重用标识符注册单元格的部分。当你创建你的 tableView 时,确保添加这个:
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
关于swift - 在 UITableViewCell 中编辑自定义标签(swift 3 xcode),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623621/