I have a very simple RootView Controller ->Detail View Controller, to display a list of core data object and show details on a selected object in the DetailViewController.
The DetailViewController is a UITableView with custom UITableViewCell that has a UITextField to allow user edits.
I am able to display the table, able to edit the text field and so on. However, I am not sure how to actually update the manage object once the user chooses the Done button or cancel the changes upon a Cancel button action.
I understand I can probably achieve this by using a EditViewController, that can be used to edit one property at a time. But, I am interested in a solution where I could support inline editing in the DetailViewController. Any suggestions would be very helpful.
Thanks,
Custom UITableView Cell code
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.selectionStyle = UITableViewCellSelectionStyleNone;
_textField = [[UITextField alloc] initWithFrame:CGRectZero];
[_textField setTextAlignment:UITextAlignmentLeft];
[_textField setReturnKeyType:UIReturnKeyDone];
[_textField setClearButtonMode:UITextFieldViewModeWhileEditing];
[_textField setDelegate:self];
[[self contentView] addSubview:_textField];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void) layoutSubviews {
[super layoutSubviews];
CGRect contentRect = [self.contentView bounds];
// In this example we will never be editing, but this illustrates the appropriate pattern
if ([self isEditing]) {
self.textLabel.frame = CGRectZero;
self.textField.frame = CGRectMake(contentRect.origin.x + kCellLeftOffset, kCellTopOffset, contentRect.size.width - kCellLeftOffset, kCellHeight);
}
else {
CGRect frame = CGRectMake(contentRect.origin.x + kCellLeftOffset, kCellTopOffset, 90, kCellHeight);
CGRect textFrame = CGRectMake(frame.origin.x + frame.size.width + kCellLeftOffset, kCellTopOffset, 180, kCellHeight);
self.textLabel.frame = frame;
self.textField.frame = textFrame;
}
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
if (!editing)
[_textField resignFirstResponder];
}
-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
return [self isEditing];
}
The text editing should really be handled in a controller rather than a view. Your custom cell is a view, the appropriate place to put the text field delegate methods would be the detail view controller.
Here is your solution:
Pass the
managedObjectModelof your root view controller to your detail view controller as a property. Do the same with the managed object to be edited.In the delegate methods of your text field, update the object’s properties as appropriate
Finally, in your handlers of the
DoneandCancelbuttons, save or discard the changes: