Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow a user to edit the text in a UITableView cell

I am creating a "favorite pages" menu in my tableview application, where users can save their favorite web pages and then navigate to them easier through the menu.

For ease of remember which link is which, I want to allow the user to click a button that says "edit," somehow select the cell that they want to edit the name of, and then type in the new name and have the cell rename itself to what the user typed in. I am currently using the built in settings application to save the link data.

I don't need to know every aspect of what I just asked. I just want to know if it is possible for the user to edit the cell text of a tableview, and what methods I would use to do so.

I've seen other questions that cover similar ground, but generally from a more programmatic basis.

like image 671
dgund Avatar asked Feb 01 '12 02:02

dgund


2 Answers

The user cannot directly edit the cell text of a tableview. (Technically, it would be the cell.textLabel.text). However, if they go into an "edit" mode, you could easily display a UITextField in the cell (or in a modal view) which is prepopulated with the current value, let them edit it, save and then update the cell.textLabel.text value yourself.

like image 169
Rayfleck Avatar answered Nov 05 '22 05:11

Rayfleck


Your UITableView cells are created here, usually

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

(one of the delegates for the UITableView).

So if you subclass UITableViewCell and expose a text property, you can do what you want, including holding a UITextField instance in the Cell. Make sure to use the dequeue stuff as you would normally.

Then, when the user touches the UITableViewCell you can give the UITextField the focus:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.thatTextFieldIMentioned becomeFirstResponder];
}

If you make the UITableViewCell subclass a UITextFieldDelegate and make it the delegate for the text field, you can easily handle these annoyingly hard-to-remember methods:

- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"yeah inform someone of my change %@", textField.text);
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
like image 22
Dan Rosenstark Avatar answered Nov 05 '22 05:11

Dan Rosenstark