我想限制 IOS 应用程序 textField
中的字符。 Stack Overflow中给出的所有方法我都试过了,所以才问这个问题。
这里我使用了一个标签(安全代码)和一个文本字段(5 个字符)。
我在 viewcontroller.m
文件中给出了以下代码,但没有工作。
myTextField.delegate = self
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 5);
}
最佳答案
在 ViewController.h 中,<UITextFieldDelegate>
应该加上。
在你的viewDidLoad中,myTextField.delegate = self
应该加上。
然后,限制字符数:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= 5 && range.length == 0)
return NO;
return YES;
}
适合我。试试吧。
编辑:
另一方面,您的代码也应该可以正常工作。再次检查您的代码。
关于ios - 如何将 iOS 应用程序中文本字段的字符限制为最多 5 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14847040/