1

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.

- (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;

  }
Ketan Shinde
  • 1,847
  • 4
  • 18
  • 38

2 Answers2

1

You're only using the replacementString value for your calculation, which is the last character that was typed, not the whole the whole string.

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.

You need to get the whole text of the quantityText textfield and use that. You could get that by taking textField.text and then replacing the specified range with the replacementString.

To be honest though it's a lot easier just to register for the UITextFieldTextDidChangeNotification instead of using the textfield:shouldChangeCharactersInRange:replacementString: method.

See this answer for details.

Community
  • 1
  • 1
Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103
  • i am not get u properly. how notification is helpful to me as i gone through answer provided by you in link. how can i work all with this. – Ketan Shinde Feb 07 '12 at 10:45
  • It will give you the full text typed by the user every time they press a key, not just the last character they typed. – Nick Lockwood Feb 07 '12 at 11:05
0
- (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

Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
Krrish
  • 2,256
  • 18
  • 21