简体   繁体   中英

iOS: How to access values from UITextField which is in custom cell of tableview

I have a table view with custom cells which contains multiple text fields. I want to get values entered in text fields on a button click on somewhere in cellForRowAtIndexPath. Is it possible ?

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

Above image is the screenshot of text fields which are in table view cell.

you can get UITextField with help of Tag Functionality.

Suppose you have 3 UITextField in 1 Cell .

give Tag to UITextField in cellForRowAtIndexPath Method in following way.

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

for get UITextField you can use following line.

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

A possibility to do so is to define a custom cell and make Outlets and Properties for your each textfields. Later from view controller get the cell and access the element from custom cell.

eg,

Custom Cell:

@interface CustomCell : UITableViewCell
{

}

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

@end

ViewController

-(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;
}

Note: I assume you work for the visible cells only.

For the case other than this, you have to update your datasource(UITableView datasource NSDictionary, NSArray, Custom Object Collection etc) (using delegates, protocols) whenever your UITextField ends edit.

Then your button code will look like this: (Assuming your data source is an array object some class CustomObject and has a property yourRequireddata which keeps data of 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;
}

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM