Leon
Leon

Reputation: 417

call a method with the "Return" (Done) Button of the keyboard

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 :)

Upvotes: 2

Views: 8257

Answers (2)

ingh.am
ingh.am

Reputation: 26792

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
}

Upvotes: 13

mani_007
mani_007

Reputation: 602

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>

Upvotes: 1

Related Questions