Chandu
Chandu

Reputation: 695

Adding TextFields in a TableView To an Array

I've Created a textField to all the cells in the table view.

self.field = [[UITextField alloc]initWithFrame:CGRectMake(20, 44, 222, 31)];
self.field.delegate = self;
[cell.contentView addSubview:self.field];

So All the rows got a textfield. But I want to Access them individually. One of my seniors asked me to add them to an array and use them and left me this one line code

[self.array addObject:self.field];

So what's next? how should I use them?

Upvotes: 2

Views: 2666

Answers (4)

ichanduu
ichanduu

Reputation: 425

UITextField *fieldOne = [arrayName objectAtIndex:locationOfTheTextField];

Upvotes: 1

sujith1406
sujith1406

Reputation: 2822

another way to do this is by knowing the indexpath of the textfields superview(ie the uitableview cell)..by knowing the indexpath.row u know which cells textfield u r using

first get the superview of the textfield in textfield delegate method like -textfielddidendediting

UITableviewCell *cell=(UITableviewCell*)[textfield superview];
NSindexPath *indexpath=[self.tableview indexPathForCell:cell];

now u can use this indexpath to find to which cell the textfield belongs and save the value accordingly

Upvotes: 1

EXC_BAD_ACCESS
EXC_BAD_ACCESS

Reputation: 2707

Instead You can assign tag(Your indexpath.row) to yourTextField and You can get the data.Like

self.field.tag = indexPath.row;

For getting the Data from Field you can go with,

for (int indexVal=0;indexVal<noOfRows; indexVal++)
{
        NSString *inputData=(UITextField *)[self.view viewWithTag:indexVal].text;   
        //Add this to array or something and use it
} 

Upvotes: 0

Ishu
Ishu

Reputation: 12787

You are creating it in wrong way, you make a global object of textField then hows you know from which row's textField what text you are going to pick.

So you need to make textFields locally for each row and set tag to each textField accroding to indexPath.row.

UITextField *txt = [[UITextField alloc]initWithFrame:CGRectMake(20, 44, 222, 31)];
txt.delegate = self;
txt.tag=indexPath.row;
[cell.contentView addSubview:txt];

Upvotes: 0

Related Questions