テキストフィールドの最大文字数制限を修正
-
19-08-2019 - |
質問
Cocos2dのテキストフィールドに固定文字制限を適用するにはどうすればよいですか
解決
UITextFieldの最大文字数を修正するには、ユーザーが固定長を超えて文字列を編集しようとした場合にfalseを返すUITextFieldデリゲートメソッドtextField:shouldChangeCharactersInRange
を実装できます。
//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;
}
上記の例は、ユーザーがテキストフィールドの最後(最後の文字)で編集している場合にのみ機能します。入力テキストの実際の長さ(ユーザーが編集している場所に関係なく、カーソルの位置に関係なく)を確認するには、これを使用します。
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