Reputation: 16793
I have a textfield in the MyCustomCell
, and set the textfield delegate in the cellForRowIndexPath
tableview delegate. When user changes the textfield value and it calls textFieldShouldEndEditing
. All it works.
However, I wonder how to know which textfield (indexPath) is changed?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
// use this if you created your cell with IB
cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0];
// otherwise use this
cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// now set the view controller as the text field delegate
cell.textField.delegate = self;
}
// configure cell...
return cell;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Upvotes: 0
Views: 370
Reputation: 615
You Can Try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
// use this if you created your cell with IB
cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0];
// otherwise use this
cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// now set the view controller as the text field delegate
cell.textField.delegate = self;
textField.tag = indexPath.Row;
}
// configure cell...
return cell;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
NSLog("Selected Cell is:%@",textField.tag);
[textField resignFirstResponder];
return YES;
}
Upvotes: 1
Reputation: 397
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
if ([[[textField superview] superview] isKindOfClass:[MyCustomCell class]]) {
MyCustomCell *cell = (MyCustomCell *)[[textField superview] superview];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
// this is what you want.
}
return YES;
}
Upvotes: 2
Reputation: 19156
Set UITextField
tag in your cellForRowAtIndexPath
method. If there is only one section in your tableview you can set the row as tag. Like this.
cell.textField.delegate = self;
cell.textField.tag = indexPath.row;
And in your textFieldShouldEndEditing
method you can check the tag.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
int row = textField.tag;
[textField resignFirstResponder];
return YES;
}
Upvotes: 2