noblerare
noblerare

Reputation: 11853

How do I access a custom TableViewCell by index?

In Swift 3, is there a way to access a UITableViewCell by index (e.g. 0)?

The big picture idea of what I am trying to do is that I have a TableViewController and have a custom UITableViewCell (call it MyCell) with an imageView that I want to clear out (i.e. imageView.image = nil).

However, I am having trouble figuring out how to set the imageView to nil within the TableViewController since I can't access the cell itself. Any help would be greatly appreciated.

Upvotes: 0

Views: 708

Answers (2)

Vahid
Vahid

Reputation: 3496

func cellForRow(at indexPath: IndexPath) -> UITableViewCell?

source: https://developer.apple.com/reference/uikit/uitableview/1614983-cellforrow

example:

let index = IndexPath(row: 3, section: 2)
let cell = self.table.cellForRow(at index)

For accessing to image you can do as bellow:

self.table.cellForRow(at index).image

Upvotes: 3

dylanthelion
dylanthelion

Reputation: 1770

Like this (I'm assuming you mean by indexPath; if you want to get an array index of visible cells, please modify your question or reply):

let myCell = self.tableView.cellForRow(at: myIndexPath) as! myCustomCellType

...all of the 'my...' object types are whatever you want them to be; 'myIndexPath' is the indexPath of your cell.

Edit

How to access UIImageView ?

By the above code you get the cell object now use below code to access the imageView

cell.imageView.image  = "img_name.png"

Upvotes: 2

Related Questions