views:

343

answers:

2

I am trying to implement a hello world application for the iPhone and i've worked through some. However i can't figure out how to get the keyboard to go away. I've seen this and no it doesn't help (i have resignFirstResponder in my code). I have connected the relevant textfield to the file's owner as a delegate. Here is the code that determines whether the keyboard should dissapear:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == textField)
    {
     [textField resignFirstResponder];
    }
    return YES;
}

I'm sure this should be ridiculously obvious, but i cant find the answer. Thanks in advance for your help!

+2  A: 

First off, just to clarify: you should connect the text field's delegate to the file's owner, not the file's owner's delegate to the text field. That may sound confusing, but you can check it easily by selecting your text field in Interface Builder and checking that its "delegate" connection points at the file's owner.

Next, what happens if you take out the if statement in your code? Linking the text field's delegate to the file's owner and then changing your code to:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [theTextField resignFirstResponder];
    return YES;
}

should produce the desired results.

If it still doesn't work, check that the file's owner's class is the same as the class you have that method implemented in. For example, if the code is in RootViewController.m, then you want to specify that the file's owner is an instance of RootViewController in Interface Builder.

Tim
I think i wasn't being clear about the delegate yes, i have it wired as you specified. For some reason, removing the if statement cleared things up nicely. thanks!
RCIX
A: 

your code

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == textField)
    {
        [textField resignFirstResponder];
    }
    return YES;
}

is sort of fail.

You didn't call resignFirstResponder to the parameter of the delegate method, you called it to what I assume is an instance variable. This should have been written as follows:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == [self textField]) {
        [theTextField resignFirstResponder];
    }
    return YES;
}
Jonathan Sterling
Of course, to use the code I provided, textField must be a property. In reality, you shouldn't really ever communicate with instance variables. That is what properties are for. Properties provide a nice, happy, memory-managed encapsulation for you to do things to instance variables with.
Jonathan Sterling