Ios 如何在目标c中的目标方法中获取textfield的引用?
我在Ios 如何在目标c中的目标方法中获取textfield的引用?,ios,objective-c,xcode,uitableview,Ios,Objective C,Xcode,Uitableview,我在UITableViewCell的UITextField上添加了目标。我使用了下面的代码 cellIdentifier = @"TextFieldCell"; TextFieldCell *txtCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; txtCell.indexPath = indexPath; [txtCe
UITableViewCell
的UITextField
上添加了目标。我使用了下面的代码
cellIdentifier = @"TextFieldCell";
TextFieldCell *txtCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
txtCell.indexPath = indexPath;
[txtCell.textFieldData addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
现在,对于目标中的方法,如下所述
-(void)textFieldDidChange :(UITextField *) textField{
}
我在下面的TextCell中添加了indepath
属性。在callback方法中,我希望获取已添加目标的textfield的引用,以便访问indepath
属性。
我想在回调方法中获取
txtCell.textFieldData
。请告诉我如何操作?在tableview数据源方法中添加一行或多行,以查找您选择的文本字段或标识您点击的文本字段
txtCell.textFieldData.delegate = self;
txtCell.textFieldData.tag = indexPath.row;
txtCell.textFieldData.text = [self.yourarrayName objectAtIndex:indexPath.row];
[txtCell.textFieldData addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
在您的操作中,您可以获得当前文本字段的引用
-(void)textFieldDidChange :(UITextField *) textField{
NSLog(@"textField values== %%@",textField);
}
更新和示例
如果您想更新文本字段,请按照如下步骤操作
-(void)textFieldDidChange :(UITextField *) textField{
NSLog(@"this is your current textfield values== %%@",textField);
[self.yourarrayName replaceObjectAtIndex:textField.tag withObject:textField.text];
if (textField.text.length > 0)
{
[textField setNeedsDisplay];
// do something whatever you need
}
}
您可以对
UITextField
进行子类化,以包含类型为nsindepath
的属性
@interface MRTextField : UITextField
@property (strong, nonatomic) NSIndexPath *indexPath
@end
在故事板/xib中,只需选择UITextField
,并将其类更改为MRTextField
。在textfield单元格中为此textfield创建一个出口,其类型将为MRTextField
,而不是UITextField
。从序列图像板控件+将文本字段拖到UIViewController
并将其设置为代理
然后只需实现UITextField
shouldChangeCharactersInRange
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
MRTextField *tempTextField = (MRTextField *)textField;
//access the indexPath property using tempTextField.indexPath
return YES;
}
注意:文本字段没有用户在上述委托方法中执行的最新更改,例如,如果用户在文本字段中键入s,则文本将包含文本,然后将s添加到字符串中。您可以自己添加它并使用上述方法保存到模型中,也可以在以下委托中执行操作:
-(void)textFieldDidEndEditing:(UITextField *)textField{
MRTextField *tempTextField = (MRTextField *)textField;
//access the indexPath property using tempTextField.indexPath
}
首先,您必须将标记赋予特定单元格的textfield,然后在target方法中,您可以获得该标记,然后使用以下命令:
TextFieldCell *txtCell = [tableview cellForRowAtIndexPath:tag]
现在您可以在textfielddichange
中访问--txtCell.textFieldDatatextField
是txtCell.textFieldData
的引用。在textfielddichange中,textField是您选择的textField引用。您可以使用textField的标记属性