Referencing UITextFields in a custom cell in a UITableView

279 views Asked by At

I have a static UITableView that has 5 cells like below:

custom UITableViewCell

When the user selects the top row I need to execute a method which will populate data into the second row.

When de-queing the cell's I added a target action like so:

[cell.upperTextField addTarget:self action:@selector(upperTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

I get notified of the event. How do I reference the second text view (find the CellForRowAtIndexPath) to enter data into it?

I can't use the didSelectRow since I have disable selection - the user can only tap into one of the provided TextFields.

3

There are 3 answers

3
hemkaran_raghav On BEST ANSWER

Use a custom cell for that and find your cell object using CellForRowAtIndexPath method and now you can easily find your textfield like below.

MyCellView myCell = [myTableView cellForRowAtIndexPath:<your index path>];
myCell.firstTextField 

or

myCell.secondTextField

If you want to change the text. You can easily change the text of textField.

1
thorb65 On

if think it would be easier by subclassing UITableViewCell and handle that internal in that cell. Then you could directly access the correct textfield.

Create a .h and .m wth

@interface YourCell : UITableViewCell

Then name that class in the interfacebuilder inspector section for your storyboard cell. Then you call the cell in cellForRowAtIndexPath

YourCell *tempCell = (YourCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
1
Greg On

Add tag values to your UITextFields:

textField1.tag = 1;
textField1.tag = 2;

In your upperTextFieldDidChange: get reference to your superview of your textField and find view by tag:

-(void)upperTextFieldDidChange:(id)sender
{
    UITextFields *tf = (UITextFields*)sender;
    int currentTag = tf.tag;
    // Do any validation if needed
    //Get reference to text field superview
    UIView *v = [tf superview];
    // Get reference to your second text field
    int tfTag = currentTag == 1 ? 2 : 1;
    UITextField *anotherTextField = (UITextField*)[v viewWithTag: tfTag];
    // Execute your method do other stuff here
}

Hope this help