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.
The only method I found is a tableview delegate
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
[cell dealloc]
}
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
.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With