Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell text filed disappear data on scrolling the tableview

I have a UITableView with custom cells, those cells contain some textFields. Here when I enter some data in textFields and I scroll the table view data it disappears, I think because every time it's creating new cell.

I resolved this issue by using an array and inserting every cell in that, but here I am not able to reuse cells, so we are wasting memory.

Can you tell me prefect way how I should handle this behavior?

like image 235
sachin Avatar asked Dec 22 '25 23:12

sachin


2 Answers

Use an array to store the value of the every text field and set the value of the desired text field in the

- (UITableViewCell *)tableView:(UITableView *)tTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

method

like image 123
Jason McTaggart Avatar answered Dec 24 '25 12:12

Jason McTaggart


It sounds as though it has something to do with how you are creating cells in the tableView:cellForRowAtIndexPath: method. But without seeing your implementation I can only make general suggestions (add your implementation to your question so people can be a bit more specific with their answers).

If you are worried about memory then use the UITableView's inbuilt cell reuse feature by creating your cells in the following way:

NSString *identifier = @"reuseIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
cell.textLabel.text = @"text relating to index path";

The above will check the tableView to see if there are any available cells for reuse. If there are none then nil will be returned. This is where you create a cell using the initWithStyle:reuseIdentifier: method which marks the cell as being suitable for reuse if it is scrolled out of view. This means that you will only ever instantiate, at maximum, the total number of cells that are visible at once, which keeps your table's memory footprint nice and low.

Note that we set the cell's textField.text outside of the nil check - this is to ensure that if we have retrieved a reusable cell we will overwrite its old text content with the text content relevant to the indexPath being passed into the method.

like image 39
Barjavel Avatar answered Dec 24 '25 14:12

Barjavel