如何限制objective-c中的数字和特殊字符

时间:2014-03-05 07:38:21

标签: objective-c

在文本字段中我想限制像(1234567890)和特殊字符这样的数字,但我想允许使用字母数字字符。我怎么想这样做?

3 个答案:

答案 0 :(得分:0)

使用UITextField委托方法

textField:shouldChangeCharactersInRange:replacementString:

要检查即将被替换的字符串,如果允许,则返回yes,否则返回no。

以下是一些更多信息。

Apple UITextField Delegate

答案 1 :(得分:0)

尝试以下代码

+ (BOOL)isNumber:(NSString *)value {  

    if ( (value == nil) || ([@"" isEqualToString:value]) ) {  
        return NO;  
    }  

    int l = [value length];  

    BOOL b = NO;  
    for (int i = 0; i < l; i++) {  
        NSString *str =   
        [[value substringFromIndex:i]   
         substringToIndex:1];  

        const char *c =   
        [str cStringUsingEncoding:  
         NSASCIIStringEncoding];  

        if ( c == NULL ) {  
            b = NO;  
            break;  
        }  

        if ((c[0] >= 0x30) && (c[0] <= 0x39)) {  
            b = YES;  
        } else {  
            b = NO;  
            break;  
        }  
    }  

    if (b) {  
        return YES;  
    } else {  
        return NO;  
    }  
} 


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {  
    if ( (string != nil) && (string != @"") ) {  
        if (![self isNumber:string]) {  
            return NO;  
        }  
    }  
    return YES;  
}   

答案 2 :(得分:0)

您需要编写NSFormatter并将其分配到文本字段。这是NSFormatter的示例实现,它使用NSRegularExpression来验证NSTextField内容。

@interface XXNameElementFormatter : NSFormatter
@end

@implementation HcNameElementFormatter {
    NSRegularExpression *_re;
}

- (id)init {
    self = [super init];
    if (self) {
        [self initRegularExpression];
    }
    return self;
}

- (void)awakeFromNib
{
    [self initRegularExpression];
}

- (void)initRegularExpression
{
    NSError *reError;
    _re = [NSRegularExpression regularExpressionWithPattern:@"^[a-z]*$" options:NSRegularExpressionCaseInsensitive error:&reError];
    NSAssert(_re != nil, @"Error in regular expression, error: %@", reError);
}

- (NSString *)stringForObjectValue:(id)obj
{
    return obj;
}


- (BOOL)getObjectValue:(out __autoreleasing id *)obj forString:(NSString *)string errorDescription:(out NSString *__autoreleasing *)error
{
    *obj = string;
    return YES;
}

- (BOOL)isPartialStringValid:(NSString *__autoreleasing *)partialStringPtr proposedSelectedRange:(NSRangePointer)proposedSelRangePtr originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString *__autoreleasing *)error
{
    NSParameterAssert(partialStringPtr != nil);
    NSString *partialString = *partialStringPtr;
    NSRange firstMatch = [_re rangeOfFirstMatchInString:*partialStringPtr options:0 range:NSMakeRange(0, partialString.length)];
    return firstMatch.location != NSNotFound;
}

@end