我可以限制UITextField的字符集吗?

gar*_*uan 1 iphone cocoa-touch uitextfield uikit uikeyboard

我有一个位图字体,它没有每一个字符,如重音字符(éîü等)或符号,如"¥"或©我用来在游戏的Highscore表中显示用户名.

是否可以将UIKit键盘限制为某些字符,或仅允许UITextField中的某些字符?或者我是否必须推出自己的输入机制?我想和老派,街机风格,一次一个字母"东西"就可以了.

Pfh*_*yer 9

使用intregus提到的UITextFieldDelegate方法,您可以非常轻松地完成此操作:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // Only characters in the NSCharacterSet you choose will insertable.
    NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}
Run Code Online (Sandbox Code Playgroud)


Rya*_*IRL 5

您可以尝试使用以下UITextFieldDelegate方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
Run Code Online (Sandbox Code Playgroud)