2

is there anyboby who can give me an example method that is called by pressing the return button of the keyboard and saves the text of a textview (that was typed in before) in the nsuserdefaults?

thanks a lot :)

Leon
  • 417
  • 3
  • 11
  • 24

2 Answers2

13

Make sure your UITextField has a return key type set to UIReturnKeyGo (this is for the image on the keyboard):

theTextField.returnKeyType = UIReturnKeyGo;

Then use this method to do what ever you want to do:

- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
    // Tell the keyboard where to go on next / go button.
    if(textField == theTextField)
    {
        // do stuff
    }

    return YES;
}

To get the text from the textfield just call theTextField.text and save as you wish!

Swift Version

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // Tell the keyboard where to go on next / go button.
    if textField == theTextField {
        // do stuff
    }

    return true
}
Jalil
  • 1,167
  • 11
  • 34
ingh.am
  • 25,981
  • 43
  • 130
  • 177
  • Why do we need the `if` statement inside this method? Is it to check against multiple text fields within the same view controller? – abc123 Mar 20 '13 at 16:04
  • 1
    If you have more than one textfield, you might want to only have it submit on the last one for example. – ingh.am Mar 20 '13 at 16:07
  • Remember that you need to change the keyboard style to match this however. – ingh.am Mar 20 '13 at 16:08
  • This post also helped by explaining a bit more about the delegate: http://stackoverflow.com/questions/6190276/how-to-make-return-key-on-iphone-make-keyboard-disappear – abc123 Mar 20 '13 at 16:14
  • 1
    Don't forget to hook up your controller as the delegate of the `UITextField` and implement `UITextFieldDelegate`. – devios1 Jun 30 '14 at 21:24
0

If you are adding UITextField to an UITableCell dynamically, you need to also set delegate for it:

    self.textfield.delegate = self;

also on the the header file you need to add this:

    @interface YourController: UIViewController <UITextFieldDelegate>
mani_007
  • 628
  • 7
  • 14