修复文本字段中的最大字符限制

Md *_*din 1 objective-c cocos2d-iphone

如何在Cocos2d中对文本字段强加固定字符限制?

Bra*_*Guy 5

要修复UITextField中的最大字符数,您可以实现UITextField Delegate方法textField:shouldChangeCharactersInRange,如果用户尝试编辑超过固定长度的字符串,则返回false.

//Assume myTextField is a UITextField
myTextField.delegate = self;

//implement this UITextFiledDelegate Protocol method in the same class
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > kMaxTextFieldStringLength)
        return NO;
    else
        return YES; 
}
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚测试过,如果用户在文本字段的开头继续编辑,它就会失败.我建议你做一个:if([textField.text length]> kMaxTextFieldStringLength)而不是测试if(range.location> kMaxTextFieldStringLength)另一个注意事项,范围是0. (2认同)