aarti aarti - 6 months ago 14
Objective-C Question

objective c-how can i decrement the number in uilabel when text is type in texfield in ios?

here is my code, in this i can limit up maximum number which have to filled in textfield, but i need to decrement the label which have already value 15 it should be decremented when i started typing on textfield by 1

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//_length -= 1;
//[self.lbl setText:[NSString stringWithFormat:@"%d", self.length]];
_lbl.text = [NSString stringWithFormat:@"%lu",[AnswerText.text length]];

NSUInteger newLength = [AnswerText.text length] + [string length] - range.length;
return (newLength > 15) ? NO : YES;


}

Answer

First of all set delegate for this textField. Try this code:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == AnswerText) {
        if (([AnswerText.text length] + [string length]) > 15) {
            return NO;
        }

        _lbl.text = [NSString stringWithFormat:@"%ld", (long)(150 - ([AnswerText.text length] + [string length]))];
    }

     return YES;
}

Hope this might help you.