How to refer to a cell outside of cellForRowAtIndexPath

Viewed 23019

I am trying to update a label in a cell outside of

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

by using

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell

that does not return an error, but the label cell.time.text is not updated.

7 Answers

You shouldn't be using touchUp inside targets. You might run into problems when scrolling fast and pressing buttons. You press one row button but when you release the finger that is another row button releasing the action. Also you might run into memory leaks. If you add a target you must remove it later! If you want to add targets it is better to use TouchDown event instead to avoid such problems. I personally use tapGestures. Then when the viewdisappear I find the cell which has a tapGesture and remove it for memory leaks issues.

Swift 5.1 ++

Safe way to get custom cell refrence outside cellForRowAtIndexPath:

Here is Code :

let indexPath = IndexPath(row: 5, section: 0)
 
if let cell = self.yourTableView.cellForRow(at: indexPath) as? customCell {
       
     // Get all custom cell property refrence 
     // Do what ever you want ..
     
} 

Note:

You can get only visible cell refrence

Related