我试图将一个整数变量从 cellForRowAtIndexpath 传递到自定义 UITableViewcell。我尝试使用以下代码,但自定义单元格中的整数变量始终为零。
// TableView intialisation
tableView = UITableView() // delcared in class level
tableView.frame = self.view.bounds
tableView.delegate = self
tableView.dataSource = self
tableView.separatorColor = .clear
self.view.addSubview(tableView)
tableView.register(TodoListTVCell.self, forCellReuseIdentifier: "cell")
self.view.bringSubviewToFront(tableView)
// Cell for row at indexpath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TodoListTVCell
cell.picsTag = objectsArray[indexpath.row].picsTag
return cell
}
// custom tableview cell
class TodoListTVCell : UITableViewCell{
var picsTag : Int!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
print("index tag \(picsTag)")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
PS:我不想使用全局变量,提前致谢。
答案 0 :(得分:0)
创建自定义函数并在设置所有单元格属性后调用此函数。
// Cell for row at indexpath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TodoListTVCell
cell.picsTag = objectsArray[indexpath.row].picsTag
cell.printPicsTag()
return cell
}
// custom tableview cell
class TodoListTVCell : UITableViewCell{
var picsTag : Int!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func printPicsTag() {
print("index tag \(picsTag)")
}
}