I have created a dynamic table, but I’m facing an issue when I try to access the content of a text field in the first cell. The textfield I get is always empty, even though I enter some text in it before calling the action.
Here is my code. Could you help me to find what’s wrong in it ?
CustomNameCell.h
@interface CustomNameCell : UITableViewCell
@property (retain, nonatomic) IBOutlet UITextField *nameTextField;
@end
CustomViewController.h
@interface CustomViewController : UITableViewController
@property (retain, nonatomic) IBOutlet UITableView *tableview;
- (IBAction)search:(id)sender;
@end
CustomViewController.m :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 1) {
static NSString *CellIdentifier = @"nameCell";
CustomNameCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[CustomNameCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
return cell;
}
...
and the action when clicking a button, where I try to get the content of the textfield :
- (IBAction)search:(id)sender {
static NSString *CellIdentifier = @"nameCell";
CustomNameCell *nameCell = [_tableview dequeueReusableCellWithIdentifier:CellIdentifier];
here nameCell.nameTextField.text is always equal to @""
Why is my text field always empty ?
Thank you for your help 😉
You shouldn’t call
[_tableview dequeueReusableCellWithIdentifier:CellIdentifier];within your –(IBAction)search:(id)senderas it is a mechanism to reuse a cell during the creation of your tableView. Instead of creating new cell when you are scrolling your tableview you are reusing some cells you have previously created.Bottom line: use instead the
cellForRowAtIndexPathto access a cell at a specific row in your section and if you want the first cell of the first section it would be: