obuseme / TestTableViewAndTextField

Demonstrates a problem of using a UITextField in a prototype cell in a UITableView
0 stars 0 forks source link

Possible solution #1

Open haaakon opened 8 years ago

haaakon commented 8 years ago

Save the textField to a variable in the ViewController when first getting it from cellforRow. If you have multiple textFields you can store the links to them in an array.

A more MVC way of doing it is to implement it as a delegate pattern that tells some other class every time the textfield text is changed

obuseme commented 8 years ago

Thanks for the idea! So, connecting the textField to an IBOutlet in the ViewController was an initial thought for me. If I did that though, Xcode didn't like that: image

I did not try saving it to a strong property while the tableview was being drawn. I'll try that.

The delegate pattern is a good idea, and that's what I initially implemented. I think a drawback of that solution in my specific use case was that it created a tight coupling between the text field's delegate and the uiviewcontroller, so it was like this triangle of dependencies, in that the viewcontroller had hooks into both the tableviewcell where the textfield was, and the uitextfielddelegate, and tableviewcell had a strong reference to the uitextfielddelegate.

After all that, I realized I could just add a header view to the tableview and put the textfield there, since my requirement was that the textfield scroll with the tableview, but always be at the top, and only appear once. Then I could create an IBOutlet from the viewcontroller to the textfield, and the text property always reflected what was entered into the field!

haaakon commented 8 years ago

Yeah i think it would be best to store it as attribute after the cell was allocated in cellForRow.

But good that it worked!

kevnm67 commented 8 years ago

I just ran in to this issue and the following solved the issue for me:

// block methods for UITextField from: https://github.com/haaakon/UITextField-Blocks
// in my tableview datasource class I did the following:

- (void)configureTextFieldCell: 
    if (self.configureTextFieldBlock) {
        // Sends the info to view controller to set the cells custom label and the text fields text.
        self.configureTextFieldBlock(cell, indexPath,[self titleForRowAtIndex:indexPath]);
    }
    tCell.textField.didEndEditingBlock = ^(UITextField *textField) {
    // Sends the title of the text field a user just finished editing + the cells indexpath.
            self.textFieldFinishedWithData(textField.text, indexPath);
        };
}