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

时间:2009-01-23 06:01:59

标签: objective-c cocos2d-iphone

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

3 个答案:

答案 0 :(得分:5)

要修复UITextField中的最大字符数,您可以实现UITextField委托方法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; 
}

答案 1 :(得分:2)

要使用户能够使用退格键,您应该使用这样的代码(当您按退格键时,range.length只有零):


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 >= 10 && range.length == 0) return NO; return YES; }

答案 2 :(得分:1)

上述示例仅在用户正在文本字段末尾(最后一个字符)进行编辑时才有效。要检查输入文本的实际长度(无论用户在哪里编辑 - 光标位置),请使用:

myTextField.delegate = self;

//implement this UITextFiledDelegate Protocol method in the same class
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (range.location > kMaxTextFieldStringLength)
        return NO;
    else
        return YES; 
}
相关问题