Jobs Jobs - 3 months ago 7
Swift Question

Is it possible to derive the indexPath if you know the row?

Okay, I'm going to try to break this down as simply as I am able. I have a tableView in a ViewController. I have two prototype cells for the table. I am reusing the cells multiple times to populate the table.

In one of the cells, I've added gesture recognizer to the

label
through which I'm making a
textField
visible on place of the label and hiding the
label
. Now I want the labels text to change to what I've entered in the
textField
when I'm done using the
textField
and hit the return key. So i implemented the
UITextFieldDelegate
protocol in the
viewController
. I've also added tags to each of the textFields in the cell so that I know what
textField
is returning and what row the textField is in.

Basically, what I want to know is if there is any way to get the indexPath if I already know the indexPath.row?

For the gesture recognizers, i was able to work around this issue by getting the indexPath from the tapped location:

func genderTapped(sender: UITapGestureRecognizer) {

let tapLocation = sender.locationInView(self.profileInfoTable)
let indexPath = self.profileInfoTable.indexPathForRowAtPoint(tapLocation)

let cell = self.profileInfoTable.cellForRowAtIndexPath(indexPath!) as! editUserDataCell
cell.savedUserInput.hidden = true
cell.userDetailTextfield.becomeFirstResponder()
cell.userDetailTextfield.hidden = false
cell.userDetailTextfield.text = cell.savedUserInput.text!
}


I need the
indexPath
so that I can refer to the elements contained within a cell. Can anyone offer any insights? Has anybody tried a similar approach? Is there any way I can access the cell by just using the row?

Answer

If you are able to get the indexPath inside the GestureMethod then you can create one instance property of type NSIndexPath store its value inside that Gesture's method and later used the indexPath inside textFieldShouldReturn delegate method, something like this.

var selectedIndexPath: NSIndexPath?

func genderTapped(sender: UITapGestureRecognizer) {

    let tapLocation = sender.locationInView(self.profileInfoTable)
    self.selectedIndexPath = self.profileInfoTable.indexPathForRowAtPoint(tapLocation)

    let cell = self.profileInfoTable.cellForRowAtIndexPath(self.selectedIndexPath!) as! editUserDataCell
    cell.savedUserInput.hidden = true
    cell.userDetailTextfield.becomeFirstResponder()
    cell.userDetailTextfield.hidden = false
    cell.userDetailTextfield.text = cell.savedUserInput.text!
} 

Now use this self.selectedIndexPath inside UITextFieldDelegate method.

Edit: From your question's comment you have told that you have just one Section so you can also create indexPath from that textField's tag this way.

func textFieldShouldReturn(textField: UITextField) -> Bool {
    let indexPath = NSIndexPath(forRow: textField.tag, inSection: 0)
    //Or You can use self.selectedIndexPath also 
}