Reputation: 717
I tried to access custom tableView cell textfield from outside tableView like this :
for i in 0..<NameCounter {
let indexPath = IndexPath(row: i, section: 0)
guard let cell = sampleTableView.cellForRow(at: indexPath) as? sampleCellView else{
return
}
if let text = cell.txtName.text, !text.isEmpty {
let value = text
print("Getting NameText : \(value)")
}
if let text = cell.txtNote.text, !text.isEmpty {
let value = text
print("Getting noteText : \(value)")
}}
But the problem is above method you can only get visible cell of tableView except cell is nil. and because I guard it to avoid nil cell, I did not get all textfield value.
If I remove the guard like this :
let cell = sampleTableView.cellForRow(at: indexPath) as! sampleCellView
It will crash and got some cell is nil.
How to access all textfield value from outside tableView and got all cell (cell maynot nil)?
I have multiple tableView, and inside each tableView cell, I put txtName and txtNote. I want to detect which txtName and txtNote is being edited, so I can put in the right model.
note: txtName is textfield and txtNote is textView
Upvotes: 0
Views: 977
Reputation: 100523
This return
let cell = sampleTableView.cellForRow(at: indexPath) as! sampleCellView
nil and crash for any cell that's not visible as of the fact that the table cells are reusable , you need to save the user typing for each cell to model ( tableView dataSource array ), then get the values from it
var model = [String]()
// inside cellForRowAt
cell.textView.delegate = self
cell.textView.tag = indexPath.row
}
@objc func textViewDidChange(_ tex: UITextView) {
model[tex.tag] = tex.text!
}
class VC:UIViewController,UITextViewDelegate {
Upvotes: 0
Reputation: 3666
As a good standard practise, there should be no need to get values from the UITableViewCells
. You should instead get the values from the Model that is presented in the UITableView
, based on some logic as per the need.
Further, when it is needed to access any text that was typed on UITableViewCell
, then it should be updated in the associated model first and should be accessed from there.
Behind the scene UITableViewCell are re-used and only the cells currently visible will show you actual data if you access it from UITableView. Hence persisting cell's entered values to some array / dictionary for later use is the option.
Upvotes: 0
Reputation: 4277
You shouldn't rely on the values being taken from the cell labels, text fields etc.
Once a cell goes off-screen - it gets thrown to a pool for later reuse, and it may even get deallocated.
You should keep the view state
inside some array, and then you can SAFELY get any value at any index.
If you have 1000 cells, perhaps only 10-20 will be visible at any time, and maybe 40-50 or so in the reusable cells pool. If you are at index path row 100 - obviously the cells after index path row 150 will be nil
.
Upvotes: 1