Search code examples
iosswifttableviewcell

How to find the indexPath of a custom cell, when the cell contains a specific item?


I have a custom cell containing several items, including a name and age.

In another view controller, in the viewDidLoad, I set the cell with specific names etc.

In viewDidDisappear, I would like to know what is the age for the name "X".

However I have no reference to the cell whatsoever, and I am trying to find out what is the indexPath of the cell containing name "X" to get its corresponding age value.

I have stumbled upon this:

let indexPath = NSIndexPath(forRow: <#Int#>, inSection: <#Int#>)

In order to use this:

let cell: customCellTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as! customCellTableViewCell

This is how I set up cellForRowATIndexPath:

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


    let cell: customCellTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! customCellTableViewCell

    let row = indexPath.row


    let memb = self.arrayMemb[indexPath.row]

    cell.setCell(memb.name, age: memb.age)

    return cell

}

And the I would be able to proceed. However I do not know how to get the NSIndexPath based on the name value "X".

Any idea how to do this, Thank you infinitely,


Solution

  • If you know the name, get the member from the data source (model) rather than from the cell (view)

    The code assumes that memArray contains a member with the given name in any case.

    let givenName = "John Doe"
    
    let filteredMembers = memArray.filter {$0.name == givenName}
    let age = filteredMembers[0].age