Detecting current input character in UITextField (iOS)

I want to know the current input character that the user just entered. The layout of the old and new input lines seems to work, but this should be the last thing I would like to try. Any suggestion? I think there are some methods in the iOS SDK that can do this better.

+3
source share
3 answers
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

from UITextFieldDelegate will help you.

It is intended not only to replace text, but also each time a key is pressed on the keyboard. (the length of the range will be 0, and the location will be the current insertion position).

. : http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html#//apple_ref/doc/uid/TP40006991-CH3-SW9

+4

,

[textField addTarget:self action:@selector(compareInput) forControlEvents:UIControlEventEditingChanged];

-(void)compareInput
{
    if ([textField.text isEqualToString:compareString])
        NSLog(@"They're the same!");
}

:

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

, . string .

, , , foo UITextField:

: f, :

[textField addTarget:self action:@selector(compareInput) forControlEvents:UIControlEventEditingChanged];

compareInput , f textField.text:

-(void)compareInput
{
    NSLog(textField.text); //prints `f`
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(textField.text); //prints nothing
    return YES;
    //after returning YES, textField.text will contain `f`
}

: o, :

[textField addTarget:self action:@selector(compareInput) forControlEvents:UIControlEventEditingChanged];

compareInput , fo textField.text:

    -(void)compareInput
{
    NSLog(textField.text); //prints `fo`
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(textField.text); //prints `f`
    return YES;
    //after returning YES, textField.text will contain `fo`
}

, , , , !

+3

This method will show the current entry in UITextField

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *letters;
    if ([textField.text isEqualToString:@""]){
        letters = string;
    }else if ([string isEqualToString:@""]){
        if ([textField.text length] > 0) {
            letters = [textField.text substringToIndex:[textField.text length] - 1];
        }
    }else{
        letters = [textField.text stringByAppendingString:string];
    }

    NSLog(@"letters %@\n", letters);

    return YES;
}
0
source

All Articles