質問

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??

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top