Ios 将数据传递给自定义UITableViewCell类
我正在尝试将一个整数变量从CellForRowatinexPath传递到自定义UITableViewcell。我尝试使用下面的代码,但在自定义单元格中整数变量始终为零Ios 将数据传递给自定义UITableViewCell类,ios,swift,tableview,Ios,Swift,Tableview,我正在尝试将一个整数变量从CellForRowatinexPath传递到自定义UITableViewcell。我尝试使用下面的代码,但在自定义单元格中整数变量始终为零 // TableView intialisation tableView = UITableView() // delcared in class level tableView.frame = self.view.bounds tableView.dele
// 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:我不想使用全局变量,提前谢谢。创建自定义函数并在设置所有单元格属性后调用此函数
// 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)")
}
}
init
是您看到的nil
的地方吗?如果是这样,这是意料之中的,因为初始化器将在您向属性分配任何内容之前完成。是的,这就是在设置picsTag之前调用@paulw11init函数的问题。picsTag
在init
中不可能是非nil的,但这真的不重要。你的代码绝对不错,但并不清楚你想要实现什么。您正在以正确的方式设置值,但在错误的位置访问它。