限制用户只在UITextField中输入一个单词

时间:2011-04-29 19:41:46

标签: objective-c uitextfield

有没有办法只允许用户在UITextField中输入一个单词?如果是这样,怎么样?

这是我正在使用的当前代码:

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

_disallowedCharacters = [NSCharacterSet whitespaceCharacterSet];

for(int i = 0; i < [_searchBox.text length]; i++){
    unichar c = [_searchBox.text characterAtIndex:i];
    if (![_disallowedCharacters characterIsMember:c])
    {
        return NO;
    }
}
return YES;
}

2 个答案:

答案 0 :(得分:4)

使用UITextFieldDelegate协议:

- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered
{
    for (int i = 0; i < [textEntered length]; i++)
    {
        unichar c = [textEntered characterAtIndex:i];
        if ([disallowedCharacters characterIsMember:c])
        {
            return NO;
        }
    }
    return YES;
}

其中disallowedCharactersNSCharacterSet,其中包含键盘不应接受的字符,即空格,标点符号,数字等:

self.disallowedCharacters = [NSCharacterSet characterSetWithCharactersInString:@" ,.123"];

答案 1 :(得分:2)

对于检查空格和换行符的字符集(对于Evan的答案),您可以使用

self.disallowedCharacters = [NSCharacterSet whitespaceAndNewlineCharacterSet];

如果你想检查除空格和换行符之外的字符,请创建一个mutableCopy并添加你想要的任何内容:

NSMutableCharacterSet *set = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];
[set formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
[set formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet];
[set addCharactersInString:@"whatever you want"];
...
self.disallowedCharacters = [[set copy] autorelease];
[set release];

NSCharacterSet docs可以很好地概述您可以使用的字符集。