views:

88

answers:

2

I have a class that needs to ask the user a question and wait for the users response to determine the next action. What would be the best way to do this? Using a delegate? How? I have a UITextField and a UITextField in the class.

Thanks

A: 

Yes, you should use a delegate, and link that to the keyboard's done button (I'm assuming that you're presenting the user a keyboard). Simply link your delegate to the return key of the keyboard, and that should do the trick.

TahoeWolverine
+1  A: 

It all depends upon how you wish for the user to submit the data. The most user friendly way is to do as TahoeWolverine explained and implement - (BOOL)textFieldShouldReturn:(UITextField *)textField from UITextFieldDelegate. In order to use this, the class that implements textFieldShouldReturn: must have <UITextFieldDelegate> protocol in its interface declaration; moreover, the textfield in question must have the UITextFieldDelegate-implementing class set as its delegate. In most cases those would look like this:

@interface SomeViewController : UIViewController <UITextFieldDelegate> {
    UITextField *myField;
}

@property (nonatomic, retain) IBOutlet UITextField *myfield
@end

and somewhere in the implementation:

[[self myField] setDelegate:self];

Finally, implementing the UITextFieldDelegate protocol:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == [self myField]) {
         [self doSomethingWithText:[[self myField] text]];
    }
}

Hope that helps.

Jonathan Sterling
Yep, I've actually used textFieldShouldReturn in another app, great suggestion.
Xcoder