Zach Lucas
Zach Lucas

Reputation: 1641

How to click UIButton when user hits return on keyboard

I want to be able to send a message as soon as the user touches return on the on-screen keyboard. I have a send UIButton, how do I make it listen for the return key? Thanks!

Upvotes: 0

Views: 434

Answers (2)

Logan
Logan

Reputation: 53132

Your button Method:

- (void) btnPressed:(id)sender {

{

Add Delegate Stuff if you haven't

@interface YourViewController : UIViewController <UITextFieldDelegate>

And when you call your textField:

yourTextField.delegate = self;

Then, you should just call the button's action method in the delegate shouldReturn method:

- (BOOL) textFieldShouldReturn:(UITextField *)textField {

    [self btnPressed:nil];
    // whatever else you need

    return YES;

}

Upvotes: 1

esqew
esqew

Reputation: 44714

Hook textFieldShouldReturn: and send a message to the button or directly to the function that button calls.

If you're using UITextView, it takes a bit of trickery:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{       
    if (textView == messageInput) {
        if ([text isEqualToString:@"\n"]) {
            // your code goes here
            return NO;
        }
    }
    return YES;
}

Upvotes: 0

Related Questions