简体   繁体   English

设置字符限制时缺少textField中的最后一个字符

[英]Missing last character from textField when setting character limit

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. 我创建了一个应用程序,它将呼叫一个5位数的医院分机号码,用户通过在其前面输入交换机号码输入到textField。

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. 由于所有扩展都是5位数,我宁愿应用程序在计数5位数时启动telprompt,而不是让用户按下呼叫按钮。 I have this so far but for some reason it is missing off the 5th digit when it shows the telprompt. 到目前为止,我有这个,但由于某种原因,它显示telprompt时缺少第5位数字。 (ie if the user enters "12345" the telprompt only shows "1234". Any ideas why? (即如果用户输入“12345”,则telprompt仅显示“1234”。任何想法为什么?

- (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 . 这里的问题是你与shouldChangeCharactersInRange混淆了。 The text in the TextField will only change when this function returns YES . 仅当此函数返回YES时,TextField中的文本才会更改。 You are reading the self.numberTextField.text before returning YES for the last character. 您正在读取self.numberTextField.text然后为最后一个字符返回YES Example : say you want to enter 01234 . 示例 :假设您要输入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. 直到1234,你的条件失败,因为长度不是5.但是一旦你输入数字4 ,在实际上将4添加到文本字段的文本之前,如果允许输入的字符被输入,将调用shouldChangeCharactersInRange以符合。 This is the point where you are now reading the textfield's text which is still 1 character short. 现在,您正在阅读文本字段的文本,该文本仍然是1个字符短。 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. textFieldDidChange: function。 Hope this helps you:) 希望这可以帮助你:)

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

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