开发者

Ignore Tab character in UITextField... (iPad app)

I have a TableView with TextFields in each cell and I want to those textfields ignore the character tab (\t).

When the tab key is pressed, the textFie开发者_运维技巧ld:shouldChangeCharactersInRange method it's not called

Does anyone knows how to do this? I know that there is no tab key in the iPad keyboard but the blutooth and dock ones do and triggers a really weird behavior.

Thanks


This seems to be a problem with the tab (\t) character. This character is not handled like normal characters (e.g. a, b, c, 0, 1, 2, ...) and thus the

              - (BOOL)textField:(UITextField *)textField 
  shouldChangeCharactersInRange:(NSRange)range 
              replacementString:(NSString *)string;

delegate method won't ever be called.

The result of using a tab on e.g. an external keyboard or in the simulator is that a currently active textfield resigns it's first responder status and the result of

[textField nextResponder]

will become first responder instead.

What IMO currently is a bug (iOS SDK 4.3) is that the delegate method

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField

is only called once (when you return yes) and when you reselect the same textfield and use the tab key again, the method won't be called again.


Implement this method:

Add this in your AppDelegate.m

- (NSArray *)keyCommands {
static NSArray *commands;

static dispatch_once_t once;
dispatch_once(&once, ^{
    UIKeyCommand *const forward = [UIKeyCommand keyCommandWithInput:@"\t" modifierFlags:0 action:@selector(ignore)];
    UIKeyCommand *const backward = [UIKeyCommand keyCommandWithInput:@"\t" modifierFlags:UIKeyModifierShift action:@selector(ignore)];

    commands = @[forward, backward];
});

return commands;
}

Add this method in the ViewController.m or subclass of UITextField in which you want to handle the TAB key event

- (void)ignore {

    NSLog(@"Your Action");
} 

Described in: How do you set the tab order in iOS?


Check to make sure the delegate for the UITextField is set either in IB or code. Check to make sure your .h file has the UITextFieldDelegate specified

All should work now.


I think this is possible, but difficult. Basically, I would try to ensure that when the text field becomes the first responder, no other view can become the first responder. Then, pressing tab will do nothing. Then, you would have to reverse this effect when another view that actually could become first responder is selected, or when the text field resigns first responder.


Have you tried checking other characters in the range you're calling shouldChangeCharactersInRange with? That will make sure it's not being called properly (vis a vis a problem with the tab key specifically).

more on shouldChangeCharactersInRange here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜