Bot
Bot

Reputation: 11855

Enable all textfields in UITableViewCell when in Edit mode

I have a bunch of custom UITableViewCells with a label and textbox. I have the textbox disabled but I want to make it so when the user taps the Edit button it will make the textboxes editable. How can I do this so that ALL the UITextFields in the UITableView become enabled?

I have

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.navigationItem setHidesBackButton:editing animated:YES];

    if (editing) {

    }
}

but cannot add the textbox enable in there since I don't have access to all the textfields. Would I need to add code to grab all the cells and loop through them and enable the textfields?

Upvotes: 2

Views: 2125

Answers (2)

Jack Lawrence
Jack Lawrence

Reputation: 10772

Edit your subclass of UITableViewCell and register your instances for an editing notification in your subclass's viewDidLoad or init method:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disableTextBox) name:@"EditingIsEnabled" object:nil];

And implement a method called disableTextBox that disables the text box for that cell.

Then in your setEditing:animated method, post the notification when you want to start editing:

[[NSNotificationCenter defaultCenter] postNotificationName:@"EditingIsEnabled" object:self];

Override the method dealloc in your UITableViewCell and remove yourself as an observer, or you'll crash:

[[NSNotificationCenter defaultCenter] removeObserver:self];

If you're not using ARC, make sure to call [super dealloc]. If you're using ARC, do not call super.

You can do the same thing when you want to disable all the cells, just post a notification with a different name like EditingIsDisabled.

Let me know if you need me to flesh out the code a bit more.

Edit: I like DBD's method better in this situation.

Upvotes: 2

DBD
DBD

Reputation: 23233

I would do this by setting a isEditing BOOL on your UITableViewDelegate in the setEditing:animated: method and just updating visible cells when the value is changed.

NSArray *visibleCells = [myTable visibleCells];
for (MyTableViewCell *cell in visibleCells)
    cell.textField.enabled = isEditing;

Then, using your UITableViewDelegate again, update new cells as they appear in tableView:willDisplayCell:forRowAtIndexPath:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.textField.enabled = isEditing;
}

Upvotes: 9

Related Questions