题
如何固定的字符限制可以在cocos2d上的文本字段强加?
解决方案
要修复中字符的的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;
}
其他提示
要启用用户使用退格键时,应使用这样的代码(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;
}
以上仅示例工作,如果用户在文本字段(最后一个字符)的端部进行编辑。针对实际长度检查(不管所述用户是editing-光标位置)的输入文本使用这样:
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;
}
不隶属于 StackOverflow