UITableViewCell will disappear

I made a UITableView and contained some custom UITableViewCells, in the first cell (for example, named cell0) there are some UITextFields for input, when I look at the View table, cell0 will disappear from the top of the screen, then how can I get the UITextField text in cell0?

cellForRowAtIndexPath will return zero.

+6
source share
5 answers

According to the Apple Documentation near cellForRowAtIndexPath: it returns "An object representing a table cell or nil if the cell is not visible or indexPath is out of range."

A UITableViewCell is a view according to the MVC Pattern . Therefore, I would prefer to save the model object - perhaps it's as simple as an NSString instance - to save the text in a cell if I were you. You can observe the change in UITextField by adding an observer to the UITextFieldTextDidChangeNotification button to your controller.

 - (void)textFieldDidChangeText:(NSNotification *)notification { // Assume your controller has a NSString (copy) property named "text". self.text = [(UITextField *)[notification object] text]; // The notification object property will return the UITextField instance who has posted the notification. } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Dequeue cell... // ... if (!cell) { // Init cell... // ... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeText:) name:UITextFieldTextDidChangeNotification object:yourTextField]; } // Other code... // ... return cell; } 

Remember to remove the observer in -dealloc .

+1
source

The only method I found is a tableview delegate

 - (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { [cell dealloc] } 
+11
source

As UITableViewCells leave the visible area of ​​the UITableView , it is actually removed from the table view and put back into the reuse queue. If selected for reuse, it will be returned by dequeueReusableCellWithIdentifier:

There is no callback if the cell is removed from the view. However, prepareForReuse is called in the cell just before it returns dequeueReusableCellWithIdentifier:

What do you end up trying to do?

+1
source

You need to save the text somewhere (e.g. NSArray ) at the time of its change.

0
source

You can initialize the text field as an instance variable.

look like this:

.h

 UITextField *textfiled; 

.m

 -(void)viewDidLoad { //init textfield } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //init cell... [cell addSubview:textfield]; return cell; } 
-2
source

Source: https://habr.com/ru/post/951181/


All Articles