Can you please help me.
In UITextField
when we provide a placeholder text its placeholder string will be gone when we enter any character. How can I achieve
There is my solution using UITextField text property
+(BOOL)shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
textField:(UITextField *)textField
mask:(NSString *)mask withMaskTemplate:(NSString *)maskTemplate{
NSString * alreadyExistString = @"";
if (string.length == 0) {
alreadyExistString = textField.text;
for (int i = range.location; i >= 0; i--) {
unichar currentCharMask = [maskTemplate characterAtIndex:i];
unichar currentChar = [alreadyExistString characterAtIndex:i];
if (currentCharMask == currentChar) {// fixed value and _
continue;
}else{
alreadyExistString = [alreadyExistString stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@"_"];
break;
}
}
textField.text = alreadyExistString;
return NO;
}else{
alreadyExistString = [textField.text stringByReplacingCharactersInRange:NSMakeRange(range.location, 1) withString:string];
}
NSMutableString * validText = [[NSMutableString alloc] init];
int last = 0;
BOOL append = NO;
for (int i = 0; i < alreadyExistString.length; i++) {
unichar currentCharMask = [mask characterAtIndex:i];
unichar currentChar = [alreadyExistString characterAtIndex:i];
BOOL isLetter = [[NSCharacterSet alphanumericCharacterSet] characterIsMember: currentChar];
BOOL isDigit = [[NSCharacterSet decimalDigitCharacterSet] characterIsMember: currentChar];
if ((isLetter && currentCharMask == '#') || (isDigit && currentCharMask == '9')) {
[validText appendString:[NSString stringWithFormat:@"%c",currentChar]];
}else{
if (currentCharMask == '#' || currentCharMask == '9') {
break;
}
if ((isLetter && currentCharMask!= currentChar)|| (isDigit && currentCharMask!= currentChar)) {
append = YES;
}
[validText appendString:[NSString stringWithFormat:@"%c",currentCharMask]];
}
last = i;
}
for (int i = last+1; i < mask.length; i++) {
unichar currentCharMask = [mask characterAtIndex:i];
if (currentCharMask != '#' && currentCharMask != '9') {
[validText appendString:[NSString stringWithFormat:@"%c",currentCharMask]];
}
if (currentCharMask == '#' || currentCharMask == '9') {
break;
}
}
if (append) {
[validText appendString:string];
}
NSString *placeHolderMask = textField.text;
NSString *sub = [validText substringWithRange:NSMakeRange(range.location, 1)];
placeHolderMask = [placeHolderMask stringByReplacingCharactersInRange:NSMakeRange(range.location, 1) withString:sub];
textField.text = placeHolderMask;
return NO;
}
@property (nonatomic,strong) NSString * maskTemplate;// like: _2_-__-__A
@property (nonatomic,strong) NSString * mask;// like: #2#-99-##A
#Edit 1 There is also some more code I have implemented which move the cursor to the underscore location. If someone need help. Please comment I will help you.
#Edit 2
Problems I have facing using this approached
Thanks, Still waiting for if there is any other workaround using Placeholder String.