I've created an app which will call a 5 digit hospital extension number that the user enters in to a textField by prefixing it with the switchboard number.
As all extensions are 5 digits I would rather the app initiate a telprompt when it counts 5 digits rather than have the user press a call button. I have this so far but for some reason it is missing off the 5th digit when it shows the telprompt. (i.e. if the user enters "12345" the telprompt only shows "1234". Any ideas why?
- (BOOL)textField:(UITextField *)numberTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [self.numberTextField.text length] + [string length] - range.length;
if (newLength == 5) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt:(01233633331)(P)(%@)", self.numberTextField.text]]];
}
return YES;
}
The problem here is that u got confused with shouldChangeCharactersInRange
. The text in the TextField will only change when this function returns YES
. You are reading the self.numberTextField.text
before returning YES
for the last character. Example: say you want to enter 01234. till 1234 your condition fails as the length is not 5. But as soon as u enter number 4, before 4 is actually added to the textfield's text, shouldChangeCharactersInRange
will be called to conform if the entered character should be allowed to enter. This is the point where you are now reading the textfield's text which is still 1 character short. Solution: Add a notification like this
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
And u can write
if (newLength == 5) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt:(01233633331)(P)(%@)", self.numberTextField.text]]];
}
inside textFieldDidChange:
function. Hope this helps you:)