These are some notes on the KitchenSink example covered in Lecture 15 of Paul Hegarty’s iPhone course at Stanford. Go there to watch the video for the full story.

What’s going on

This example let’s a user click a button called ‘Add Label’ which then smooshes them off to a modal view controller where they are asked to enter the name of a label they would like to see appear.

This example shows how to make a model view controller (which is just a regular view controller with the transition set to ‘modal’ rather than ‘push’).

The more interesting bit is how the segue and delegate work.

Basically the ‘prepare for segue’ set’s things up that the view you are transitioning to needs. In our case we setup the question, and some answer text we’d like to display in the initial textfield box.


-(void) prepareForSegue:(UIStoryboardPopoverSegue *)segue sender:(id)sender
    if ([segue.identifier hasPrefix:@"Create Label"]) {
        AskerViewController *asker = (AskerViewController *) segue.destinationViewController;
        asker.question = @"What do you want your label to say?";
        asker.answer = @"Label text";
        asker.delegate = self;

Then in the view controller we are transitioning to, we read it off:


    [super viewDidLoad];
    self.questionLabel.text = self.question;
    self.answerTextField.placeholder = self.answer; // preset in segue
    self.answerTextField.delegate = self;

To communicate back to the calling view controller we came from we use delegates. Asker sets up a protocol, which KitchenSink implements, and this is how to tell the caller what text the user entered in the textfield.

Then when the user finishing typing (or the textfield loses the caret) this gets called (because we implement UITextFieldDelegate).

-(void)textFieldDidEndEditing:(UITextField *)textField
    self.answer = textField.text;
    if (![textField.text length]) {
        [[self presentingViewController] dismissModalViewControllerAnimated:YES];
    } else {
        // need to communicate!
        [self.delegate askerViewController:self didAskQuestion:self.question andGotAnswer:self.answer];

If the textfield is blank, just dismiss the dialog. Else send our delegate a message containing the text the user entered and they will dismiss the dialogue.


-(void)askerViewController:(AskerViewController *)sender didAskQuestion:(NSString *)question andGotAnswer:(NSString *)answer
    // the user has typed something in the user view controller, got the answer, now we want to create our label
    [self addLabel:answer];
    [self dismissModalViewControllerAnimated:YES];

Here is the protocol we implement. And after grabbing the answer and creating a label, we dismiss the view controller ourselves.

That’s it! Great example of how to use delegates with model view controllers with a modal dialog thrown in.