Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell will disappear

I made an UITableView and contained some custom UITableViewCells, in the fist cell (named cell0 for example) there are some UITextFields for input, when I scroll the tableView, cell0 will disappear from the top of screen, then How can I get the UITextField's text in cell0?

cellForRowAtIndexPath will return nil.

like image 935
Mil0R3 Avatar asked Aug 07 '13 03:08

Mil0R3


3 Answers

The only method I found is a tableview delegate

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell dealloc]
}
like image 63
Damien Romito Avatar answered Oct 05 '22 23:10

Damien Romito


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

A UITableViewCell is a view, according to MVC Pattern. So I'd prefer maintaining a model object -- maybe it is as simple as a NSString instance -- to hold the text in the cell if I were you. You can observe UITextField's change by adding an observer of UITextFieldTextDidChangeNotification key 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's 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;
}

Don't forget to remove the observer in your -dealloc.

like image 22
liuyaodong Avatar answered Oct 06 '22 00:10

liuyaodong


As UITableViewCells leave the viewable area of the UITableView it is actually removed from the tableview and placed back into the reuse queue. If it is the selected for reuse it will be returned by dequeueReusableCellWithIdentifier:.

There is no callback for when a cell is removed from the view. However, prepareForReuse is called on the cell just before it is returned by dequeueReusableCellWithIdentifier:.

What are you ultimately trying to do?

like image 30
BergQuester Avatar answered Oct 06 '22 00:10

BergQuester