iOS automatically add hyphen in text field

2019-01-09 07:49发布

I'm learning iOS development and am having a hard time figuring out the various events for the controls. For a test I have a UITextField where the user is meant to input a string in the format: XXXX-XXXX-XXXX-XXXX

I want to be able to check how long the text in the field is after each entry and see if it needs to have a hyphen appended to it. I've set up my IBAction function for this but when I assign it to the "Value Changed" event it does nothing, it works fine when I set it on the "Editing Did End" but that will only call when the user exits the control.

Edit: Just to add, the "Editing Changed" event causes it to crash too. I assume this is a stack overflow or something where the setting of the text calls the event handler again.

So in short, is there any way to set an event handler for each time the user enters a character in the UITextField?

8条回答
欢心
2楼-- · 2019-01-09 08:36

You could try this:

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

It should really work with that, you should also post some code. After registering with the event you should just check the lenght of the string and add hyphen.

查看更多
The star\"
3楼-- · 2019-01-09 08:40

For something like this I would suggest using the UITextFieldDelegate to detect whenever the user types a new character. Setup your text field's delegate as follows:

[textField setDelegate:self];

Then, implement the delegate methods as appropriate:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder]; // hide the keyboard
    return NO;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // every time the length reaches four, it gets reset to 0 and a '-' is added.
    static int currentLength = 0;
    if ((currentLength += [string length]) == 4) {
        currentLength = 0;
        [textField setText:[NSString stringWithFormat:@"%@%@%c", [textField text], string, '-'];
        return NO;
    }
    return YES;
}

This may not work perfectly, but I hope it helps!

查看更多
登录 后发表回答