我的应用程序中有一个
UITableView
,其中有自定义 UITableViewCell
,其中包含 UITextField
。我想做的是当我从该行选择特定文本字段时获取该行的正确索引。
不幸的是,只有当我实际单击该行时,我才能获得该行的正确索引,而不是在选择文本字段本身时。我正在实现
<UITextFieldDelegate>
,当我选择特定的 UITextField
时,我调用该方法:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
int rowTest = [_table indexPathForSelectedRow].row;
int rowTest1 = [_cell.tireCodeField tag];
NSLog(@"the current row is: %d", rowTest1);
NSLog(@"and this row is: %d", rowTest);
return YES;
}
问题是我得到的行的值来自于该方法:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
}
接到电话。就好像
UITextField
与其所在表中的行之间存在脱节。
有没有办法让我通过选择其中的
UITextField
来获取行的索引,而不是选择行本身?
通常完成此操作的方法是为文本字段提供一个等于indexPath.row的标签,或者如果您有多个部分,则为部分和行进行某种数学组合(例如1000*indexPathSection + indexPath.row)。
好吧,假设单元格是直接超级视图或文本字段,您可以直接请求文本字段的超级视图,转换为 UITableViewCell,然后向您的 UITableView 实例询问该单元格的索引路径。这是一个例子:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
UITableViewCell *cell = (UITableViewCell *)textField.superview; // cell-->textfield
//UITableViewCell *cell = (UITableViewCell *)textField.superview.superview; // cell-->contentView-->textfield
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
return YES;
}
如果您正在寻找适用于多个 iOS 版本的更动态的解决方案,那么您可能需要使用以下引用自 @Marko Nikolovski 的内容
// Get the cell in which the textfield is embedded
id textFieldSuper = textField;
while (![textFieldSuper isKindOfClass:[UITableViewCell class]]) {
textFieldSuper = [textFieldSuper superview];
}
// Get that cell's index path
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)textFieldSuper];
此方法会向上爬行
superview
,直到遇到 UITableViewCell
。即使单元格的视图层次结构发生变化(就像从 iOS 6 到 7 一样),这也能让代码正常工作。
我想我应该发布这个稍微(!)迟到的答案,因为我多年来一直试图这样做,然后记住另一种方法(如果我这么说,我自己就是最好的方法之一)获取 的索引路径点击
UIButton
时的单元格。
以类似的方式你可以得到单元格的
CGPoint
。
-(NSIndexPath *)indexPathForTextField:(UITextField *)textField
{
CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
return [self.tableView indexPathForRowAtPoint:point];
}
-(void)textDidChangeForTextFieldInCell:(UITextField *)textField
{
NSIndexPath *indexPath = [self indexPathForTextField:textField];
// Now you can update the object at indexPath for your model!
}
我认为这比依赖 tag
或查看
superview
的更令人讨厌的方法远更简洁!
因为您似乎正在使用标签,所以使用 UITextFieldDelegate,您可以声明此方法以选择行。
-(void)textFieldDidBeginEditing:(UITextField *)textField{
int rowTest1 = textField.tag;
[myTableview selectRowAtIndexPath:[NSIndexPath indexPathForRow:rowTest1 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
[textField resignFirstResponder];
}
UITableViewCell *textFieldCell = (UITableViewCell*) [[[textfield superview]superview]superview];
NSIndexPath *indexPath = [self.editProfileTableView indexPathForCell:textFieldCell];