简体   繁体   中英

textFieldShouldReturn doesn't work (using storyboard on XCode 4)

I have a button and a textfield. I just want keyboard disappear when clicking on button. Why my code below doesn't work.

Update: I saw something about file owner. I don't understand how to do this in XCode4 I use storyboard and I can't see any file owner icon.

Update 2: I found a tut http://www.techotopia.com/index.php/Writing_iOS_4_Code_to_Hide_the_iPhone_Keyboard_%28Xcode_4%29 but it uses XIB file on XCode 4 not storyboard. How to do this with storyboard ?

myViewController.h

@interface myViewController : UIViewController <UITextFieldDelegate>
{
    UITextField *myTextField;
}

@property (retain, nonatomic) IBOutlet UITextField *myTextField;

myViewController.m

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    myTextField.delegate = self;
}

- (IBAction)DoCalc:(id)sender {
      // ...
}

Check to see if the textFieldShouldReturn function that you've written into myViewController.m is even being called. Set a breakpoint inside of it and then run the simulator. Press the return key on the keyboard. If the program doesn't break, then the function you've written isn't being called.

If it is, it's because you haven't delegated UIResponder duties to your view controller. Make sure you are delegating responder duties to your myViewController class for the UITextField that you're working with.

In storyboard, you do this by control-dragging from the UITextField widget to the yellow orb below the scene, and selecting "delegate" from the context menu that appears.

textFieldShouldReturn: should return NO to hide the keyboard. One more thing - do not set first responder to self , [textField resignFirstResponder] is enough, iOS should figure nextResponder by itself.

You can hide the keybord in this method...

- (void)textFieldDidEndEditing:(UITextField *)textField {

     [textField resignFirstResponder];
}

Remove [self becomeFirstResponder]; should do it.

resignFirstResponder is to dismiss the keyboard. while becomeFirstResponder is to open the keyboard. so in your code, you are closing then opening again the keyboard at the same time. The last action is opened the keyboard, hence it won't close.

you may look into UIResponder Class as superclass of UITextField

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM