ios - 如何将 iOS 应用程序中文本字段的字符限制为最多 5 个字符?

标签 ios ios5 ios4

我想限制 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/

相关文章:

iphone - iOS 5 : Set min and max value of input type ="date"

iPhone 应用程序无法在旧设备上运行(3G、3GS...)

iphone - 领英邀请API错误401[未授权]-iPhone sdk

iphone - iOS静态库的向后兼容性

iphone - MkMapView 在触摸时放下别针

iOS:Google 移动广告会自动处理 AdSupport 要求吗?

iphone - MPMoviePlayerViewController 从 Documents 目录播放电影 - objective-c

ios - 从 iOS 7 Beta 切换到正式版需要什么?

iOS:检测传入的短信

iOS 5.1 应用程序启动时崩溃,找不到符号 : _NSFontAttributeName