Я пытаюсь передать переменную Integer из cellForRowAtIndexpath в Custom 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: я не хочу использовать глобальные переменные, заранее спасибо.
Да, в этом проблема @paulw11
функция init вызывается до того, как вы установите picsTag.
picsTag не может быть ненулевым в init, но это действительно не должно иметь значения.
Да, но какое решение?
Ваш код абсолютно прекрасен, но не совсем понятно, чего вы пытаетесь достичь. Вы правильно устанавливаете значение, но получаете к нему доступ не в том месте.





Создайте пользовательскую функцию и вызовите эту функцию после установки всех свойств ячейки.
// 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? Если это так, этого следует ожидать, поскольку инициализатор завершится до того, как вы присвоите что-либо свойству.