Answer the question
In order to leave comments, you need to log in
How to correctly reassign a value in a function and pass it to another class?
Hello, I have a function that is called when clicking on a cell in a TableView.
Function code from TableViewController:
override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
CreateTodoTableViewCell().selectedProject = indexPath.row
}
class CreateTodoTableViewCell: UITableViewCell {
private var _selectedProject = -1
var selectedProject:Int {
set {
_selectedProject = newValue
}
get {
return _selectedProject
}
}
@IBAction func CreateTodoTextField(_ sender: UITextField) {
TodoListViewController.sharedInstance.Todos[selectedProject].append(sender.text!)
}
}
Answer the question
In order to leave comments, you need to log in
First, another method, tableView(_:didSelectRowAt:) , is used to track the click on the cell .
Secondly, as you can see from your code, you don't quite understand how to deal with class instances. That is, when CreateTodoTableViewCell().selectedProject = indexPath.row is done , then an instance (object) of the CreateTodoTableViewCell class is created and some value is assigned to its selectedProject variable . What's next? Further, at the exit from the function, this class is removed from memory, and somewhere else in your code you call a method of another object of the same class, but which has a default selectedProject , -1. You need in the didSelectRowAt methodget your real cell instead of creating it:
if let cell = tableView.cellForRow(at: indexPath) as? CreateTodoTableViewCell {
cell.selectedProject = indexPath.row
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question