So I’m trying to store a cell’s indexpath when my custom cell is created in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
I define a custom cell in class called “custom cell”, and I added a property to that class defined as such:
@property (nonatomic, strong) NSIndexPath *indexPath;
in cellForRowAtIndexPath I set the index path with customCell.indexPath = indexPath.
When I NSLog it on the very next line it returns null. Could somebody please explain why this is happening?
Edit
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EditableCell";
EditableCell *editableCell = (EditableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (editableCell == nil) {
editableCell = [[EditableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
_myTextField = [editableCell textFieldCell];
if (indexPath.section == 0){
[_myTextField setPlaceholder:@"text"];
[_myTextField setReturnKeyType:UIReturnKeyNext];
}
else if (indexPath.section == 1){
[_myTextField setPlaceholder:@"text"];
[_myTextField setReturnKeyType:UIReturnKeyNext];
}
else {
[_myTextField setPlaceholder:@"text"];
[_myTextField setReturnKeyType:UIReturnKeyDone];
}
_myTextField.keyboardType = UIKeyboardTypeDefault;
_myTextField.delegate = self;
return editableCell;
}
Where I call [self.tableview indexpathforcell:cell]
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
if (textField.returnKeyType == UIReturnKeyNext) {
UITableViewCell* myCell = (UITableViewCell*)textField.superview;
EditableCell *currentCell = (EditableCell *)myCell;
NSLog(@"INDEXPATH OF CURRENT CELL: %@",[self.tableView indexPathForCell:currentCell]);
}
}
You can determine the
indexPathof a given cell usingIf the cell needs to know it’s own
indexPath:But if it does, something’s not right!
Looking at your edited post I see the problem. You need:
The
textFieldis actually a subview of the cell’scontentView. This always seems a bit wrong to me, so another way to handle this is to make your custom cell theUITextFieldDelegate, and then create a delegate protocol for your cell. So within the cell you’d have:Then in your cell’s delegate you’ll have a reference to the cell and textField