In Uitextfield length 6 and first four char must be string remain two must be numbers when am entering first four char am trying enter 5th char keyboard change into number format then how can i write the above condition in objective c.
how to write the condition for UItextfield length and changing keyboard number format after entering four char
136 Views Asked by N.Rakesh At
4
There are 4 best solutions below
0
On
Keyboard type can be programmatically changed using its property keyboardType. Since you will have to check on every input which keyboard to place you need to implement shouldChangeCharactersInRange delegate method of UITextFieldDelegate.
Below is a sample, you can optimize it to reduce the number of reloads.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textfield == <Your texfield>) { // this condition is required in case of multiple textfields in the same view else you can skip
NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (finalString.length <= 6) {
if (finalString.length > 3) {
textField.keyboardType = UIKeyboardTypePhonePad;
} else {
textField.keyboardType = UIKeyboardTypeDefault;
}
[textField reloadInputViews];
} else {
return NO;
}
}
}
0
On
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
you can use this delegate func and add all necessary condition according to your requirements. below i am showing some sample generic code.Also you can keyboard type based on length of text
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
//length condition and also trim the string before yu check for space and dot(.)
if(textField.text?.characters.count == 6){
return false
}
//alphabetic condition
if((textField.text?.characters.count <= 4)){
if(string == "number"){
return false
}
}else if((textField.text?.characters.count > 4 )){
if(string == "alphabetic" ){
return false
}
}
return true
}
0
On
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (string.length == 0) {
if (textField.text.length == 4) {
textField.keyboardType = UIKeyboardTypeDefault;
textField.resignFirstResponder;
textField.becomeFirstResponder;
}
} else {
if (textField.text.length == 3) {
textField.keyboardType = UIKeyboardTypeNumberPad;
textField.resignFirstResponder;
textField.becomeFirstResponder;
return NO;
} if (textField.text.length < 4) {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
} else if (textField.text.length == 6) {
return YES;
}
}
return true;
}