How can I disable the decimal key on iOS keyboard

一曲冷凌霜 提交于 2020-01-16 01:03:37

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/22308313/how-can-i-disable-the-decimal-key-on-ios-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!