简体   繁体   English

shouldChangeCharactersInRange一次只能输入一位数字

[英]shouldChangeCharactersInRange taking only one digit at time

i am trying to get total value after multiplying price and quantity in to text field. 我试图在将价格和数量乘以文本字段后获得总价值。 I not getting value when quantity is 10 or having any two or three digits.This method takes only one character at time. 当数量为10或具有任何两位或三位数时,我没有获得价值。此方法一次只需要一个字符。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range    
replacementString:(NSString *)string
{
if(textField == quantityText)
{
    NSCharacterSet *charactersToRemove =[[ NSCharacterSet alphanumericCharacterSet ]  
 invertedSet];
    NSRange inRange=[string rangeOfCharacterFromSet:charactersToRemove];
    if(inRange.location != NSNotFound)
    {
        quantityText.text =[ quantityText.text 
  stringByTrimmingCharactersInSet:charactersToRemove ];
        return NO;
    }
    if ([textField text] )
    {
        float quantity = [string floatValue];
        float price = [[priceLabel text] floatValue];
        float h = quantity * price;

        amountText.text=[NSString stringWithFormat:@"%f",h];

    } 
    else
    {
        return NO; 
    }
 }    
return YES;

  }

You're only using the replacementString value for your calculation, which is the last character that was typed, not the whole the whole string. 您只使用replaceString值进行计算,这是键入的最后一个字符,而不是整个字符串。

So if I type '1' then function uses 1 as the value, then if I type '0' to make 10, your function only uses the '0' as the value. 因此,如果我键入“ 1”,则函数将1用作值,然后,如果我键入“ 0”以使10,则您的函数仅将“ 0”用作值。

You need to get the whole text of the quantityText textfield and use that. 您需要获取quantityText文本字段的整个文本并使用它。 You could get that by taking textField.text and then replacing the specified range with the replacementString. 您可以通过获取textField.text并将指定的范围替换为replaceString来实现。

To be honest though it's a lot easier just to register for the UITextFieldTextDidChangeNotification instead of using the textfield:shouldChangeCharactersInRange:replacementString: method. 老实说,尽管注册UITextFieldTextDidChangeNotification而不是使用textfield:shouldChangeCharactersInRange:replacementString:方法要textfield:shouldChangeCharactersInRange:replacementString:

See this answer for details. 有关详细信息,请参见此答案

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

this delegate method is called whenever user types a new character in to the textfield and the string object will contain only the last typed character. 每当用户在文本字段中输入新字符时,就会调用此委托方法,并且字符串对象将仅包含最后键入的字符。 so instead of using (NSString *)string use textField.text 所以不要使用(NSString *)string使用textField.text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM