sye*_*dfa 2 uitableview uitextfield ios uitextfielddelegate
我UITableView在我的应用程序中有UITableViewCell一个包含a的自定义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;
}
Run Code Online (Sandbox Code Playgroud)
问题是,我得到的行的值来自方法:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
}
Run Code Online (Sandbox Code Playgroud)
得到的.就好像UITextField它所在表中的行和行之间存在脱节.有没有办法让我选择一个特定的textField,然后得到
有没有办法通过选择行中的索引来获取行的索引UITextField,而不是选择行本身?
在此先感谢所有回复的人.
通常这样做的方法是给text字段一个等于indexPath.row的标签,或者如果你有多个部分,则是section和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;
}
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找适用于多个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];
Run Code Online (Sandbox Code Playgroud)
这种方法爬行superview直到它遇到一个UITableViewCell.即使在单元格的视图层次结构发生更改时,这也会使代码保持正常工作,就像从iOS 6到7一样.