Hofth Wayer
Hofth Wayer

Reputation: 25

Cant get correct value in UITextField using shouldChangeCharacterInRange method

i have a detailView from one of my cell, and there it is. I have 2 of UITextField, in one i type value like 100, and point is i want another UITextField to display "a+b" value. For example. in my "a" text field i have a value 45, when i type in "b" text field it suppose to change dynamically, when i type 1 it should be 46, when i type 10, it should be 55, 100 - 145. But my problem is, it gets "old" value, so when i type 10 it only add 1, when i type 100 it add 10. And when i finally click on anywhere on screen, keyboard dissapear and then it get correct value, but it suppose to change dynamically. There is piece of my code:

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


    NSString *calculator=[calculateField text];
    int modifyer = [calculator intValue];


    intProtein = [protein intValue];
    int prot = [protein intValue];


    self.intProteinResult = prot+modifyer;


    [proteinTextField setText:[NSString stringWithFormat:@"%i", intProteinResult]];


    return YES;
}

And yes, i did try search topics similiar to mine, and did tried other method stringByReplacingCharactersInRange:range withString:string. But i cant figure out how to work with it. Please help, any advice will be appreciated.

Upvotes: 1

Views: 137

Answers (1)

meatcoder
meatcoder

Reputation: 166

Use this code to assign the value to the calculator variable:

NSString* calculator = [[calculateField text] stringByReplacingCharactersInRange: range withString: string];

The above should always work no matter which character is replaced or edited.

Upvotes: 1

Related Questions