mask flexibility
HamiltonSantos opened this issue · 2 comments
I could't figure out how to implement a mask for phones with 8 OR 9 digits as it needs the mask (##) ####-#### in one case and (##) #####-#### in other, is it possible using your framework?
Hi, you solved this? Can you help me?
Yeah, I made a new version of his class:
`#import "SNMaskTextField.h"
#define MaskPhone @"MaskPhone"
NSString *kSNMaskTextFieldDefaultChar = @"#";
@implementation SNMaskTextField
-
(instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
self.mask = kSNMaskTextFieldDefaultChar;
}
return self;
} -
(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.mask = kSNMaskTextFieldDefaultChar;
}
return self;
} -
(BOOL)shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString * currentTextDigited = [self.text stringByReplacingCharactersInRange:range withString:string];//Guarda a mascara original, para alterar quando for telefone:
NSString *maskTemp = _mask;
if ([_mask isEqualToString:MaskPhone]){
//Verifica se o proximo telefone esta sendo digitado novo digito.
if (currentTextDigited.length >= 15){
_mask = @"(##) #####-####";
}else{
_mask = @"(##) ####-####";
}
}NSUInteger onOriginal = 0, onFilter = 0, onOutput = 0;
char outputString[([_mask length])];
BOOL done = NO;while(onFilter < [_mask length] && !done)
{
char filterChar = [_mask characterAtIndex:onFilter];
char originalChar = onOriginal >= currentTextDigited.length ? '\0' : [currentTextDigited characterAtIndex:onOriginal];
switch (filterChar) {
case '#':
if(originalChar=='\0')
{
// We have no more input numbers for the filter. We're done.
done = YES;
break;
}
if(isdigit(originalChar))
{
outputString[onOutput] = originalChar;
onOriginal++;
onFilter++;
onOutput++;
}
else
{
onOriginal++;
}
break;
default:
if (onOutput != currentTextDigited.length){
// Any other character will automatically be inserted for the user as they type (spaces, - etc..) or deleted as they delete if there are more numbers to come.
outputString[onOutput] = filterChar;
onOutput++;
if(originalChar == filterChar)
onOriginal++;
}
onFilter++;
break;
}
}
outputString[onOutput] = '\0'; // Cap the output string
NSString *value = [NSString stringWithUTF8String:outputString];
self.text = value;_mask = maskTemp;
return NO;
}
@end`