views:

313

answers:

1

Is possible to know when the user touch the keyboard iphone? When the user touch some button from keyboard... :/

+1  A: 

The easiest way is to use a TextField. Even is your UI Does not call for one, you can set it's frame to zero so it doesnt show up onscreen. Then you can get access to the keys pressed by using the text field's delegate callback methods.

- (void)viewDidLoad {
    [super viewDidLoad];
    //CGRectZero because we don't want the textfield to be shown onscreen
    UITextField *f = [[UITextField alloc] initWithFrame:CGRectZero];
    //We set the delegate so we can grab keypressed
    f.delegate = self; 
    [self.view addSubview:f];
    [f becomeFirstResponder];  //Show the keyboard
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
                                                       replacementString:(NSString *)string {
    if (string.length >0) {
       NSLog(@"%@ Pressed",string);
    }
    else {
       NSLog(@"Backspcae pressed");
    }        
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"return pressed");
    return YES;
}

Note: to avoid a compiler warning, make sure in your .h file the class explicitly says it implements the UITextFieldDelegate protocal. ie:

@interface MyViewController : UIViewController <UITextFieldDelegate>
Brad Smith
Can I ask if you've tested that with backspace, from what I've read elsewhere that delegate method doesn't fire on backspace, just curious
paulthenerd
i dont know... i think u dont understand me... i need to know if the user touch button keyboard...
Helena
pauls... no i havent tested that with backspace
Helena
@paulsnotes. When the backspace is pressed, the delegate method shouldchange... fires, but the string that is passed in is empty, so you can test for length == 0. I'm editing the sample coe now
Brad Smith
Brad i need check when the user toch keyboard. Im trying simulate passcode view Iphone... Settings > General > Passcode Lock.i saw that the point show when de user finish touch the keyboard
Helena
Brad!! thanxxx!!
Helena