Question

I want to disable the "." key on the number pad after detecting that the user already has entered in one decimal point into the textfield.

So the key is enabled until one decimal is detected in the textfield.

What is the best way of doing this?

EDIT: I've implemented the method below:

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

    if([string isEqualToString:@"."]) {
        decimalCount++;
    }

    if(decimalCount > 1) {

        [string stringByReplacingOccurrencesOfString:@"." withString:@""];

    }

    return YES;
}

However, it's not replacing "." with "" when decimal count is greater than 1. What am I missing so that the user can still enter new digits but not decimal points??

Was it helpful?

Solution

You can't disable the key. Implement the shouldtextField:shouldChangeCharactersInRange:replacementString: delegate method to do whatever filtering you need.

This needs to be done anyway since a user could be using an external keyboard or attempt to paste text into the text field.

OTHER TIPS

Sorry if my earlier answer mislead you. The logic was incorrect. This seems to be working for me now.

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

    BOOL result = YES;
    NSString *targetString = @".";

    if([textField.text rangeOfString:targetString].location != NSNotFound) {
        if([string isEqualToString:targetString]) {
            result = NO;
        }
    }

    return result;
}

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top