【问题标题】:iOS: How to access values from UITextField which is in custom cell of tableviewiOS:如何从 tableview 的自定义单元格中的 UITextField 访问值
【发布时间】:2014-12-29 08:28:52
【问题描述】:

我有一个包含多个文本字段的自定义单元格的表格视图。我想通过单击 cellForRowAtIndexPath 中某处的按钮获取在文本字段中输入的值。有可能吗?

上图是表格视图单元格中文本字段的屏幕截图。

【问题讨论】:

  • 你有多少个文本字段?
  • 仅适用于可见单元格?
  • 添加插座以及单元格中文本字段所需的内容。您可以为每个文本字段和单元格添加特殊标签,并为文本字段实现委托,您可以在其中使用 switch (textField.tag) 并通过 textField 的特殊标签处理每种情况。不要忘记 cell.textField.delegate = self
  • 您可以为每个单元格使用标签。当你想访问 UITextField 的值时,从 CGPoint 获取索引值。
  • 按钮是否用于保存整个表格中所做的一组更改?而且表格可以滚动,所以未保存的更改可能会从屏幕上消失?

标签: ios objective-c uitableview uitextfield


【解决方案1】:

您可以借助Tag 功能获得UITextField

假设您在 1 个Cell 中有 3 个UITextField

cellForRowAtIndexPath方法中将TagUITextField,方法如下。

[cell.TextField1 setTag:(1000 + indexPath.row)];
[cell.TextField2 setTag:(5000 + indexPath.row)];
[cell.TextField3 setTag:(9000 + indexPath.row)];

要获取UITextField,您可以使用以下行。

// Replace 1000 with your tag value
UITextField * textField = (UITextField *)[self.tableView viewWithTag:1000];
NSLog(@"Value of textfield = %@",[textField text]);

【讨论】:

  • @Abhishek : 如何从 [self.tableView viewWithTag:1000] 访问值或字符串; ?
  • @Ash 请参阅updated answer。我使用NSlog 打印UITextField 的值。你可以直接在NSString Variable.
  • 完成了,非常感谢。 :)
【解决方案2】:

这样做的一种可能性是定义一个自定义单元格并为您的每个文本字段创建OutletsProperties。稍后从视图控制器获取单元格并从自定义单元格访问元素。

例如,

自定义单元格:

@interface CustomCell : UITableViewCell
{

}

@property(nonatomic,retain) IBOutlet UILabel *label;
@property(nonatomic,retain) IBOutlet UITextField *txtField1;
@property(nonatomic,retain) IBOutlet UITextField *txtField2;

@end

视图控制器

-(IBAction)btnGetText_Click:(id)sender
{
    NSInteger requiredVisibleCell = <<indexOfYourRequiredCellHere>>;
    CustomCell *cell = [[tableView visibleCells] objectAtIndex:requiredVisibleCell];

    // Here is the text of your field
    NSString text = cell.txtField1;
}

注意:我假设您只为可见单元格工作。

对于除此之外的情况,您必须在 UITextField 结束编辑时更新您的数据源(UITableView 数据源 NSDictionary、NSArray、自定义对象集合等)(使用委托、协议)。

然后您的按钮代码将如下所示: (假设您的数据源是某个类CustomObject 的数组对象,并且有一个属性yourRequireddata 保存txtField1 的数据。

-(IBAction)btnGetText_Click:(id)sender
{
    // Here is the text of your field
    CustomObject *obj = [dataSource objectAtIndex:0]; // Pass your required index

    // Here is the text of your field
    NSString *text = obj.yourRequireddata;
}

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多