【发布时间】:2020-12-23 08:24:51
【问题描述】:
我正在尝试将一个整数变量从 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:我不想使用全局变量,提前谢谢。
【问题讨论】:
-
init是你看到nil的地方吗?如果是这样,这是意料之中的,因为初始化程序将在您将任何内容分配给属性之前完成。 -
是的,这就是问题@paulw11
-
init 函数在您设置 picsTag 之前被调用。
-
picsTag不可能在init中为非零,但这并不重要。 -
您的代码绝对没问题,但并不清楚您要实现的目标。您正在以正确的方式设置值,但在错误的位置访问它。